r/javahelp • u/osdir202 • Jul 12 '19
Understanding java concept of instantiating list of list of integers object as an arraylist
What is going on in this instantiation of List<List<Integer>> p = new ArrayList<>(); I forgot what this concept was called so googling didn't give good answers. I understand the left side part of it, literally saying what p is but not the right hand side part. Why wouldn't it be new ArrayList<ArrayList<>>(); ?
2
-4
u/Th3T3chn0R3dd1t Jul 12 '19
It should be new ArrayList<ArrayList<Integer>> by my understanding
1
u/osdir202 Jul 12 '19
That's what i thought too. But I got incompatible type error by doing that :(
2
u/BramCeulemans Jul 13 '19
Recent Java versions will use "type inference" to determine the type on the variable instantiation.
Also, I recommend using IntelliJ (even the community edition) since it will tell you this kind of stuff and prompt to replace it with the diamond operator ("<>")
6
u/chickenmeister Extreme Brewer Jul 12 '19
There are two aspects to your question that you might be asking about: the "diamond syntax", and generic type invariance. I'm going to change your question from being about
List<List<Integer>>to being aboutList<Fruit>to avoid any potential confusion with nested types, but the concept is the same.If you want to make a List to hold Fruit objects, you can write it as:
or, after Java 7, you can use the "diamond" syntax to allow the generic type parameter to be inferred on the right-hand side:
However, you couldn't declare the right-hand side to be an ArrayList of
Appleobjects (a subclass ofFruit):This is because generics are invariant. This is a type safety feature to prevent something like this from happening:
So in your particular situation, if you wanted to specify the right-hand side type arguments, it would need to be an ArrayList of Lists, not an ArrayList of ArrayLists: