3

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.

5 Answers 5

4

If you use Guava, it is as easy as:

ArrayList<Person> b;
ArrayList<Worker> a = Lists.newArrayList(Iterables.filter(b, Worker.class));
Sign up to request clarification or add additional context in comments.

Comments

3

declare your ArrayList like this :

ArrayList<Worker> myArray = new ArrayList<Worker>()

Now your ArrayList can contain only Worker and the return type of its different method will be Worker.

And then :

for(Person p : b) {
    if(p instanceof Worker)
        myArray.add((Worker)p);
}

Comments

0

Here is an example:

List<Person> b = ...

List<Worker> workers = new ArrayList<Worker>();
for (Person p : b) {
  if (p instanceof Worker) { workers.add((Worker) p); }
}

Comments

0

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.

Comments

-1

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.

2 Comments

This is not at all a good idea. The type is known at compile time; why use reflection? Maybe you should take a look at the link.
Why is it a bad idea Mark? Please help me to understand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.