如何从arraylist中提取特定对象? [英] How do you pull specific objects from an arraylist?
本文介绍了如何从arraylist中提取特定对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经创建了Animal超类,鲨鱼和鲸鱼子类.我将用什么来仅从此数组列表中打印出Shark对象?
I've made an Animal superclass, Shark and Whale subclasses. What would I use to print out just the Shark objects from this arraylist?
驱动程序:
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
从超类Animal的列表中检查特定的子类
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());
}
这篇关于如何从arraylist中提取特定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文