Say I have Animal class and Cat and Dog as its 2 subclass.
I want to return a list of both pets in one java method. So I tried the following:
public List<? extends Animal> getAllPets(...) {
List<? extends Animal> allDogs = findAnimals(...someOtherArgs, Dog.class);
List<? extends Animal> allCats = findAnimals(...someOtherArgs, Cat.class);
List<? extends Animal> retObjs = allDogs;
retObjs.addAll(allCats); // won't compile
return retObjs;
}
Is it possible to do that in Java?
Simply leave out the wildcard, like this:
List<Integer> a = Arrays.asList(1);
List<Double> b = Arrays.asList(1.0);
List<Number> c = new ArrayList<>();
c.addAll(a);
c.addAll(b);
System.out.println(c);
The above compiles and runs fine, and prints
[1, 1.0]
Try such way:
public List<? extends Animal> getAllPets(...) {
List<Dog> allDogs = findDogs();
List<Cat> allCats = findCats();
List<Animal> retObjs = new ArrayList<>(allDogs.size() + allCats.size());
retObjs.addAll(allDogs);
retObjs.addAll(allCats);
return retObjs;
}
Polymorphism allows you to store all instances of any child classes in a List
which was declared as list to store object of BaseClass
. So, in your case, you need to declare List<Animal>
, now you can store here any Cat
or Dog
.
It's no need to use ?
in your code. Delete them as the code below:
public List<? extends Animal> getAllPets(...) {
List<Animal> allDogs = findDogs();
List<Animal> allCats = findCats();
List<Animal> retObjs = allDogs;
retObjs.addAll(allCats); // won't compile
return retObjs;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.