Java – adds an object to the type of the “extended” common collection

public void addAllAnimals(ArrayList<? extends Animal> animalLikeList){
public void addAllAnimals(ArrayList<? extends Animal> animalLikeList){

 // I need to add animal objects (eg Dog,Cat that extends Animal) to animalLikeList.

}

I know it doesn't allow direct addition? Extends animal represents an unknown subtype of animal My question is: is there any way (indirectly) to add or add animal or subtypes of animal objects to animallikelikelist?

Solution

No, there is no direct legal way (except for unsafe types of actors) You can only add elements to generic collections declared with super, not extensions It may be easier to remember that the acronym PECS (producer – extensions, consumer – super) was promoted by Josh Bloch in effective Java, 2nd Edition, item 28

In fact, what you pursue seems to have no direct meaning List can be, for example, a list < dog > or a list < cat > The former can only accept dog elements, while the latter can only accept cats And since you cannot instantiate generic (unrecoverable) types in Java, you must know at run time that you are dealing with the dog list, so you only try to add dogs (and vice versa for cats) This means that you cannot create objects to be added locally and statically – you must get them in a generic way and also allow the compiler to ensure that specific types are matched every time The simplest way is to pass the element as a generic parameter Therefore, it is feasible and safe to do so:

public <E extends Animal> void addAllAnimals(List<E> animalLikeList,E animal) {
    animalLikeList.add(animal);
}

List<Dog> dogs = new ArrayList<Dog>();
List<Cat> cats = new ArrayList<Cat>();

addAllAnimals(dogs,new Dog());
addAllAnimals(cats,new Cat());

Note that this method is generic and has named type parameters to ensure that the actual generic type of the list is the same as the element type you want to add to it

You can simply replace the e parameter with collection < E > Add several objects at a time

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>