Java – nested bounded wildcards

When I try to compile the following code:

LinkedList<List<? extends Number>> numList = new LinkedList<List<Integer>>();

I got an incompatible type error:

required: LinkedList <java.util.list<? extends java.lang.Number>>
Found: LinkedList <java.util.list<Integer>>

How do I implement a LinkedList that contains elements of a list of elements with an extended number?

To be clear, I am looking for the following ways to add a list to numlist:

numList. add(new LinkedList< Integer>());

Solution

Wildcard capture will not exceed a common level So while doing so:

LinkedList<? extends Number> test = new LinkedList<Integer>();

This is not:

LinkedList<List<? extends Number>> numList = new LinkedList<List<Integer>>();

The most reasonable explanation I can think of is to treat generics as outermost invariants A LinkedList < list < integer > > is not a LinkedList < list > although list < integer > is a list , number > is extended instead of list < animal > even if the dog is an animal Here, the dog is the animal list < integer > is the list

So what is the dog / animal solution? Extension:

List<? extends Animal> animals = new List<Dog>();

Applying the same reasoning, the solution is another? Extension:

LinkedList<? extends List<? extends Number>> numList = new LinkedList<List<Integer>>();

However, because of the first, you will not be able to add anything to this list? Extension The reference type variable numlist does not know the subtype extension number of list > really, it can be ArrayList < integer >, so Java cannot provide similar security. Such things can be added to such LinkedList In order to maintain type security, the compiler will only allow null You must exactly match the generic type parameters without wildcards: LinkedList < list < integer > > numlist = new LinkedList < list < integer > > () You can add a list < integer > to such a LinkedList

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
分享
二维码
< <上一篇
下一篇>>