你能用一个for每个循环来显示一个接口吗?如果是这样的话,如何显示?此外,如何从数组列表中只显示一种类型的对象?
例如,如果您有一个实现相同接口的猫和狗类,我希望使用一个For循环来显示该接口类型的ArrayList的所有元素。
假设接口名为动物,动物是ArrayList的变量。所以会是for (animal animals: b) System.out.println (b);
吗?
你怎么才能只显示猫的对象而不显示狗的对象?
发布于 2014-12-15 10:38:34
基于您的注释,假设您有一个Animal
接口,以及实现它的类Dog
和Cat
,那么您将如何遍历列表:
List<Animal> animals = new ArrayList<Animal>();
...
foreach (Animal animal : animals) {
System.out.println(animal);
}
如果您只想显示猫:
foreach (Animal animal : animals) {
if (animal instanceof Cat)
System.out.println(animal);
}
https://stackoverflow.com/questions/27481809
复制相似问题