I've an ArrayList, for example b, and i want to get an ArrayList of Worker (Worker extend Person) from that ArrayList. b also contains other object that extends from Person.
How can i achive that? Thanks.
If you use Guava, it is as easy as:
ArrayList<Person> b;
ArrayList<Worker> a = Lists.newArrayList(Iterables.filter(b, Worker.class));
Well, i achieved my goal:
public ArrayList<Person> getList(Class<? extends Person> type) {
ArrayList<Person> newList = new ArrayList<Person>();
for (Person p : person)
if (type.isInstance(p))
newList.add(p);
return newList;
}
i extend my problem with a dinamyc child class of person. i hope is will usefull for others.
When iterating through ArrayList b as suggested by Krtek and h3r3, consider using Worker.class.isAssignableFrom(p.class). Have a look at What is the difference between instanceof and Class.isAssignableFrom(...)? for explanation on the differences.