简体   繁体   中英

List part of arraylist

I have abstract class A. Class B inherits from A, and class C inherits from B.

  • Class A has two instance variables string firstName , and string lastName
  • Class B does not have instance variables.
  • Class C has one instance variable int age.

I create function to list all object in the list. My ArrayList is created from Class B, and C.

I want to create a function just list object has age (object from class C). How?

The easiest way is to simply check the type of each object in your list:

for (Object item : yourListWithBAndCs) {
      if (item instanceof C) {
           C itemAsC = (C) item;
           // do something
      } else { ... }
}

Starting with Java8, you can use of streams and filters (Kudos to @Andrew Tobilko) for this suggestion:

list.stream().filter(i -> i instanceof C).collect(Collectors.toList());

The above will create a new list for you; containing only those objects that are instances of C.

class C extends B
{
     int age;
     ArrayList listAge;
     C()
     {
        listAge = new ArrayList();
     }
     public void addAge()
     {
    listAge.add(age);          
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM