问题
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 istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result isfalse
.
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