Why does this code compile
final ArrayList<?> dp1 = new ArrayList<String>();
But this doesn't
final ArrayList<ArrayList<?>> dp2 = new ArrayList<ArrayList<String>>();
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.
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.)
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.
No, you cannot store doubles in ArrayList<Integer> without loss of precision.
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.
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>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With