28

How can I initialize List<List<Integer>> in Java?

I know List is an interface and I can use ArrayList or LinkedList to implement List<Integer> list = new ArrayList<Integer>(), but when I initialize List<List<Integer>> list = new ArrayList<ArrayList<Integer>>(); I get error incompatible types:

ArrayList<ArrayList<Integer>> cannot be converted to List<List<Integer>>.

So how can I proceed?

1

4 Answers 4

46

Use

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

or since Java 1.7

List<List<Integer>> list = new ArrayList<>();
Sign up to request clarification or add additional context in comments.

3 Comments

thanks God, there is no explanation behind this , so we can learn?
The question is how to proceed so I'll let the OP search for terms like "invariance" and "diamond operator" :)
A little bit of explanation of how and why this works can help a lot of people.
8

You can define it as List<List<Integer>> list = new ArrayList<List<Integer>>();.

Then while defining the inner List you can take care of initialising it as ArrayList<Integer>.

Comments

3

You can define it as List<List<Integer>> list = new LinkedList();

Comments

1

You can initialize this as

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

Note that the inner List has to be an implementation of the List interface, e.g., ArrayList.
Since List is an interface, one can't have objects of the type List itself.

2 Comments

Thanks Suraj, I was fixing the html for angle brackets while you edited the comment
The OP wanted to initialize List<List<Integer>>, not List<ArrayList<Integer>>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.