• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About creating an array of ArrayList

 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I was playing with this code:


But I got a warning here because ArrayList is a raw type.

But if I do this:

I got a compilation error because I am not allowed to create a generic array.

How can I eliminate the warning?

I hope this can be made a good exam reference.
 
John Jai
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Interesting question. I got this while searching.
 
Daniel Renner
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why not use 2 Lists? Or do you need the array? Or is it maybe good to use a map instead of this array+List?
 
Stephan van Hulst
Bartender
Pie
Posts: 6126
74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Indeed. As Daniel suggested you could use
 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Stephan,
List<List<String>> matrix = new ArrayList<>();

On the right hand side, can we put this List<String>, like this List<List<String>> matrix = new ArrayList<List<String>>();?


The reason why I raise this question because this can make a good exam question.
 
Stephan van Hulst
Bartender
Pie
Posts: 6126
74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you could do that, but as of Java 7 it's unnecessary. The compiler can determine what the type arguments of the ArrayList should be from the variable you're trying to assign it to. All you have to do is use the diamond operator <>.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic