How do you pull specific objects from an arraylist?

∥☆過路亽.° 提交于 2020-01-16 18:35:10

问题


I've made an Animal superclass, Shark and Whale subclasses. What would I use to print out just the Shark objects from this arraylist?

Driver:

import java.util.ArrayList;

public class Creator {     
  public static void main(String[] args){

    ArrayList<Animal> obj = new ArrayList<Animal>();
    obj.add(new Shark("James"));
    obj.add(new Shark("Mike"));
    obj.add(new Whale("Steve"));
    obj.add(new Whale("Tommy"));

    for (Animal a: obj){
    System.out.println(a.getName());
    }
  }
}

回答1:


You can use the instanceof to check for specific subclass from the list of superclass Animal

for (Animal a: obj){
   if(a instanceof Shark)
    System.out.println(a.getName());
}



回答2:


Simple variant is just using instanceof. You can also create a getType() method in the base class, that will return, for example, a enum object or other entity to define the species in subclasses.




回答3:


Use instanceof.
From JLS 15.20.2. Type Comparison Operator instanceof

At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.

Ex: Iterate over your ArrayList

if(yourObject instanceof Shark){
    System.out.println(yourObject.getName());
}


来源:https://stackoverflow.com/questions/30022840/how-do-you-pull-specific-objects-from-an-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!