我是java新手,对以下代码有2个问题:
class Animal { }
class Dog extends Animal { }
class Cat extends Animal { }
class Rat extends Animal { }
class Main {
List<Animal> animals = new ArrayList<Animal>();
public void main(String[] args) {
animals.add(new Dog());
animals.add(new Rat());
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Rat());
animals.add(new Cat());
List<Animal> cats = getCertainAnimals( /*some parameter specifying that i want only the cat instances*/ );
}
}
1)有没有办法从Aminal列表中获取Dog或Cat实例? 2)如果是,我应该如何正确构建getCertainAnimals方法?
答案 0 :(得分:4)
Animal a = animals.get(i);
if (a instanceof Cat)
{
Cat c = (Cat) a;
}
else if (a instanceof Dog)
{
Dog d = (Dog) a;
}
注意:如果您不使用instanceof
,它会被编译,但它也允许您将a
投射到Cat
或Dog
,即使a
1}}是Rat
。尽管编译,您将在运行时获得ClassCastException
。因此,请务必使用instanceof
。
答案 1 :(得分:2)
您可以执行以下操作
List<Animal> animalList = new ArrayList<Animal>();
animalList.add(new Dog());
animalList.add(new Cat());
for(Animal animal : animalList) {
if(animal instanceof Dog) {
System.out.println("Animal is a Dog");
}
else if(animal instanceof Cat) {;
System.out.println("Animal is a Cat");
}
else {
System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal");
}
}
您还可以检查Animal的类,并将其与Animal子类进行比较。如在
for(Animal animal : animalList) {
if(animal.getClass().equals(Dog.class)) {
System.out.println("Animal is a Dog");
}
else if(animal.getClass().equals(Cat.class)) {;
System.out.println("Animal is a Cat");
}
else {
System.out.println("Not a known animal." + animal.getClass() + " must extend class Animal");
}
}
在这两种情况下,您都会将输出视为
Animal is a Dog
Animal is a Cat
基本上两者都做同样的事情。只是为了让你更好地理解。