你如何从数组列表中提取特定的 objects?
How do you pull specific objects from an arraylist?
我创建了一个动物超类、鲨鱼和鲸鱼子类。我将使用什么从这个数组列表中打印出 Shark objects?
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());
}
}
}
您可以使用 instanceof
从超类动物列表中检查特定子类
for (Animal a: obj){
if(a instanceof Shark)
System.out.println(a.getName());
}
简单变体仅使用 instanceof
。您还可以在基 class 中创建一个 getType()
方法,它将 return,例如,一个 enum
对象或其他实体来定义子 [=15] 中的物种=]是的。
使用instanceof
.
来自 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
.
例如:遍历您的 ArrayList
if(yourObject instanceof Shark){
System.out.println(yourObject.getName());
}
我创建了一个动物超类、鲨鱼和鲸鱼子类。我将使用什么从这个数组列表中打印出 Shark objects?
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());
}
}
}
您可以使用 instanceof
从超类动物列表中检查特定子类
for (Animal a: obj){
if(a instanceof Shark)
System.out.println(a.getName());
}
简单变体仅使用 instanceof
。您还可以在基 class 中创建一个 getType()
方法,它将 return,例如,一个 enum
对象或其他实体来定义子 [=15] 中的物种=]是的。
使用instanceof
.
来自 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
.
例如:遍历您的 ArrayList
if(yourObject instanceof Shark){
System.out.println(yourObject.getName());
}