r/javahelp • • 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<>>(); ?

17 Upvotes

7 comments sorted by

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 about List<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:

List<Fruit> fruit = new ArrayList<Fruit>();

or, after Java 7, you can use the "diamond" syntax to allow the generic type parameter to be inferred on the right-hand side:

List<Fruit> fruit = new ArrayList<>();

However, you couldn't declare the right-hand side to be an ArrayList of Apple objects (a subclass of Fruit):

List<Fruit> fruit = new ArrayList<Apple>(); // doesn't work

This is because generics are invariant. This is a type safety feature to prevent something like this from happening:

List<Apple> applesOnly = new ArrayList<>(); 
List<Fruit> anyFruit = applesOnly; // pretend this works
anyFruit.add(new Orange());
Apple apple = applesOnly.get(0); // Expected an Apple, but got an Orange instead!

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:

List<List<Integer>> p = new ArrayList<List<Integer>>();

1

u/osdir202 Jul 14 '19

This is a really great answer, thanks so much. So in short, we are allowed to instantiate an immediate object 'o' as any object that is its subclass but we can't make an inference for nested objects(like the List<Integer> inside the outer List< >) right?

2

u/evils_twin Jul 12 '19

It's called the diamond operator

https://www.baeldung.com/java-diamond-operator

1

u/osdir202 Jul 12 '19

Thank u i will take a look

-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 ("<>")