简体   繁体   English

列出arraylist的一部分

[英]List part of arraylist

I have abstract class A. Class B inherits from A, and class C inherits from B. 我有抽象类A。类B从A继承,而类C从B继承。

  • Class A has two instance variables string firstName , and string lastName 类A有两个实例变量字符串firstName字符串lastName
  • Class B does not have instance variables. B类没有实例变量。
  • Class C has one instance variable int age. C类具有一个实例变量int age。

I create function to list all object in the list. 我创建函数以列出列表中的所有对象。 My ArrayList is created from Class B, and C. 我的ArrayList是从类B和C创建的。

I want to create a function just list object has age (object from class C). 我想创建一个仅列出对象具有年龄的函数(来自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: 从Java8开始,您可以使用流和过滤器(对@Andrew Tobilko表示敬意)来获得此建议:

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. 仅包含作为C实例的那些对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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