Java – what is the difference between creating unbounded and bounded arrays of wildcard types?

Why is this code valid

ArrayList<?>[] arr = new ArrayList<?>[2];

But the following two are not?

ArrayList<? extends Object>[] arr = new ArrayList<? extends Object>[2];
ArrayList<? super Object>[] arr = new ArrayList<? super Object>[2];

The last two lines generate compilation errors;

Please clarify the difference

to update

On the other hand, ArrayList [] arr = new ArrayList<?> [2]; Compiled, but

ArrayList<?> arr = new ArrayList<?>();

no

Solution

Here are a few questions. Let's look at each question in turn:

>Type bindings (i.e. extension objects) can only be declared when declaring types and cannot be used when instantiating objects

for example

ArrayList's & lt;? Extended Object > AB = new ArrayList (); // Bad ArrayList's & lt;? Extended Object > AC = new ArrayList < string > ()// OK > array does not support type parameters, for example:

List < integer > [] arrayoflists = new list < integer > [2]// Compile time error list and lt; Integer > List = new list < integer > ()// well

Oracle recorded the reason for this restriction here. > Can be used when declaring a type parameter and array It was added to help avoid "unchecked exception" errors when mixing java code with and without generics This means "unknown generic type" Infinite pass card here for more details

ArrayList<?> [] arr = new ArrayList<?> [2];

It is effective for the above reasons However, its use is very limited because null can only be assigned to the declaration <& gt ;. Type of arr [0] = null; // Compile arr [1] = new object()// Compilation time error Oracle provides the following guide on using wildcards, which will help you know when to use this wildcard. > Cannot be used to instantiate an object for example

ArrayList arr = new ArrayList<?> (); // Do not compile

ArrayList arr2 = new ArrayList<(); // But the ArrayList that does this arr3 = new ArrayList< String>(); // Do it in this way.

However, the use of Only null

arr3. add(“”); // Even if you use string instantiation, it will not compile

arr3. add(null); // The compilation is very good

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