Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a complete list without iterating through it in Java

Say I have this class :

public class BaseJob{

String name;

public void setName(String name){
this.name=name;
}
public String getName()
{
   return name;
}
}

and another class that extends it :

public class DetailedJob extends BaseJob{

public void doThing();

}

Furthermore, I have this method in another class :

List<BaseJob> getSomeJobs() 

Now, my problem is :

is it possible to avoid to cast each item sequentially in the returned list of getSomeJobs, if I know for sure that every BaseJob returned is indeed a DetailedJob ?

Put differently, is there another solution than the following to cast all items in the list :

List<BaseJob> baseJobList = getSomeJobs(); 
List<DetailedJob> detailedJobList = new ArrayList<DetailedJob>();
for (BaseJob baseJob : baseJobList)
    detailedJobList.add((DetailedJob) baseJob);
like image 918
madewulf Avatar asked Feb 20 '26 23:02

madewulf


2 Answers

Probably what you want to do is parameterising the class that defines getSomeJobs.

public final class JobHolder<T extends BaseJob> {
    public List<T> getSomeJobs() {
        ...

Generally unchecked casts indicate a design problem. They are unavoidable in certain situations such as low-level implementations and when dealing with serialisation.

like image 59
Tom Hawtin - tackline Avatar answered Feb 23 '26 14:02

Tom Hawtin - tackline


If you know that all of the jobs are going to be detailed jobs, why would you put them in an arraylist of basejobs? There's no reason to, and that method would eliminate many possible errors and exceptions.

like image 21
Gordon Gustafson Avatar answered Feb 23 '26 12:02

Gordon Gustafson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!