[英]Java list/array of animals containing a variety of animals
I need a list of all the animals. 我需要一份所有动物的清单。 I have a basic
Animal
class and would like to extend it to dogs, cats, iguanas, etc. 我有一个基本的
Animal
类,并希望将它扩展到狗,猫,鬣蜥等。
Is there a good way to get them all into one List
? 有没有一种方法可以将它们全部放入一个
List
?
I want to be able to check the entire list of all animals without having to change all the previously made animals. 我希望能够检查所有动物的完整列表,而无需更改所有以前制作的动物。 They should know about all the other
Animal
classes made after them. 他们应该知道他们之后制作的所有其他
Animal
类。
You can make any number of Animal
s by extending an Animal
base class like this: 您可以通过扩展
Animal
基类来制作任意数量的Animal
:
public class Dog extends Animal {
}
Then you can declare a new list of animals. 然后你可以宣布一份新的动物名单。
List<Animal> animals = new ArrayList<Animal>();
Once you have done that, you can add any number of new objects the extend the Animal
class to your list. 完成后,您可以添加任意数量的新对象,将
Animal
类扩展到列表中。
animals.add(new Dog());
animals.add(new Cat());
animals.add(new Iguana());
You can create a List<Animal>
like this: 您可以像这样创建
List<Animal>
:
// create empty list
List<Animal> animals = new ArrayList<>();
// add any kind of animal
animals.add(new Kangaroo());
animals.add(new Butterfly());
// use that list later
int numberOfAnimals = animals.size();
for (Animal animal : animals) {
// do something
}
Things to keep in mind: 要记住的事情:
instanceof
) instanceof
) extends Animal
. extends Animal
。 ArrayList
, then make your animals an ArrayList
. ArrayList
特殊功能,那么请将您的动物ArrayList
。 But in most cases defining the variable as List
or even Collection
(or Iterable
) makes your code more flexible. List
或甚至Collection
(或Iterable
)会使您的代码更加灵活。 It is called Polymorphism . 它被称为多态性 。 So basically, you answered to your question by yourself.
所以基本上,你自己回答了你的问题。 It is perfectly legal in Java to add to collection objects of subtypes of declared collection's type.
在Java中添加已声明集合类型的子类型的集合对象是完全合法的。
You can use List<? extends Animal> animals = new ArrayList<>();
你可以使用
List<? extends Animal> animals = new ArrayList<>();
List<? extends Animal> animals = new ArrayList<>();
and then add any type of animal to the list. 然后将任何类型的动物添加到列表中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.