Use list Addall add list Compile time error extending baseClass > to another
•
Java
In this code, the last line (LIST1. Addall (List2);) Build compile time error
I do realize that if this is allowed, you can add to the same list instances of different classes But I don't know what is the right way
My GetList () method needs to return a subclass of baseClass. I can't change that requirement
I have two lists that are declared in the same way and contain objects of the same type. I need to add one to the other list Any ideas in this regard will be appreciated
BaseClass. java:
package main; public class BaseClass {}
Main. java:
package main; import java.util.ArrayList; import java.util.List; public class Main { private static List<? extends BaseClass> getList() { return new ArrayList<>(); } public static void main(String[] args) { List<? extends BaseClass> list1 = getList(); List<? extends BaseClass> list2 = getList(); list1.addAll(list2); // Compile-time error: "The method addAll(Collection<? extends capture#3-of ? extends BaseClass>) in the type List<capture#3-of ? extends BaseClass> is not applicable for the arguments (List<capture#4-of ? extends BaseClass>)". } }
Solution
You can create a new list < baseClass > and add two lists:
List<BaseClass> merged = new ArrayList<>(); merged.addAll(list1); merged.addAll(lise2);
But it might be a better idea to have GetList return list < baseClass >
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
二维码