Getting object from ArrayList <T> array of specific type in java

I have an ArrayList, for example b , and I want to get the ArrayList of Worker (Worker extend Person) from this ArrayList. b also contains another object that extends from Person.

How can i achieve this? Thank.

+3
source share
5 answers

declare ArrayListas follows:

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

Now yours ArrayListcan only contain Worker, and the return type of its other method will be Worker.

And then:

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

If you use Guava , it is as simple as:

ArrayList<Person> b;
ArrayList<Worker> a = Lists.newArrayList(Iterables.filter(b, Worker.class));
+4
source

:

List<Person> b = ...

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

, :

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;
}

dinamyc. , .

0
source

When repeating through an ArrayList bas suggested Krtekand h3r3, consider using Worker.class.isAssignableFrom(p.class). See What is the difference between instanceof and Class.isAssignableFrom (...)? to explain the differences.

-1
source

All Articles