chetan reddy
chetan reddy

Reputation: 320

How to define a 2D list

While defining a 2D dynamic array why can't I define it like this:

List<List<Integer>> t=new List<List<Integer>();

On doing so, I got an error saying:

Cannot instantiate the type List<List<Integer>>

I came to know that this is the best practice for it-

List<List<Integer>> t=new Arraylist<List<Integer>>();  

why is it so.can someone help me understand this.

Upvotes: 1

Views: 553

Answers (2)

List is an interface an as such can not use new to create a new instance of it, you need classes that implement it instead eg ArrayList

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

or since java 7
List<List<Integer>> t = new ArrayList<>();

Upvotes: 5

Fady Saad
Fady Saad

Reputation: 1189

Because in Java, List is an Interface you can't initialize it. You can do it like that;

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

Just initialize any types that implement the List Interface

Upvotes: 0

Related Questions