Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ArrayList<ArrayList<?>> list = new ArrayList<ArrayList<String>>() not compile? [duplicate]

Tags:

java

generics

Why does this code compile

final ArrayList<?> dp1 = new ArrayList<String>();

But this doesn't

final ArrayList<ArrayList<?>> dp2 = new ArrayList<ArrayList<String>>();
like image 689
Leonid Avatar asked May 24 '13 14:05

Leonid


People also ask

Why do we use List List New ArrayList?

List list = new ArrayList(); the rest of your code only knows that data is of type List, which is preferable because it allows you to switch between different implementations of the List interface with ease.

Does ArrayList add make a copy?

or when I add the object to the ArrayList, Java creates a copy and add it to the ArrayList? No, it won't copy the object. (It will copy the reference to the object.)

What is the difference between list string and ArrayList string?

The List is an interface, and the ArrayList is a class of Java Collection framework. The List creates a static array, and the ArrayList creates a dynamic array for storing the objects. So the List can not be expanded once it is created but using the ArrayList, we can expand the array when needed.

Can ArrayList store doubles?

No, you cannot store doubles in ArrayList<Integer> without loss of precision.


2 Answers

In

final ArrayList<?> dp1 = new ArrayList<String>();

The type argument ? is a wildcard which is a superset (not super-type) of String. So, ArrayList<?> is super type of ArrayList<String>.

But in

final ArrayList<ArrayList<?>> dp2 = new ArrayList<ArrayList<String>>();

The type argument ArrayList<?> (a parameterized type where ? just stands for some unkown type, and doesn't have anything to do with String) is not a wildcard, the wildcard would be ? extends ArrayList<?>, with an upper bound ArrayList<?>, which actually is a supertype of ArrayList<String>.

You can read about the rules regarding super/sub set/type in parameterized type here.

like image 64
Bhesh Gurung Avatar answered Oct 06 '22 19:10

Bhesh Gurung


It's quite complicated to understand, but in summary in your first code, String extends ? but the second one doesn't compile because ArrayList<String> does not directly inherit from ArrayList<?> you can look here if you want all the details. If you want your second example to compile you have to modify it to this :

final ArrayList<? extends ArrayList<?>> dp2 = new ArrayList<ArrayList<String>>();
like image 38
gma Avatar answered Oct 06 '22 17:10

gma