通常,如果添加到列表涉及到一个只接受列表而不接受要添加的东西的方法,那么您将在其他地方拥有一些东西,Animal
并且您会想要将其添加到列表中。在这种情况下,必须声明您的方法,以便它接受的所有列表类型都允许Animal
在其中添加一个。这必须是某个超类型的一个List<Animal>
或一个列表。它不可能是 a — 您添加的元素可能是 any 。Animal
List<Dog>
Animal
This is where the concept of the lower bound, and the keyword super
, come in. The type declaration List<? super Animal>
matches all the acceptable types as described above. On the other hand, you won't be able to get elements out of such a list in a typesafe way because they can in general be of any type at all. If a method wants to both add and get elements of declared type Animal
, the only valid type it can accept is a List<Animal>
.