• Post Reply Bookmark Topic Watch Topic
  • New Topic

Instantiating an Array of Lists  RSS feed

 
Kevin Simonson
Ranch Hand
Posts: 223
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I wrote a little Java program:

When I compile it I get the message:

LiAr.java:10: error: cannot create array with '<>'
lisArr = new List<>[ 5];
^
1 error

The compiler is complaining about line 10, not line 9, so it appears it's legal to have an array of objects of type {List< Integer>}. How then can I instantiate the array? The way I tried is definitely not working.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you cannot create an array of anything with <> in its name. Go through the Java™ Tutorials and you may find the explanation. It has to do with generics being invariant and arrays being covariant, so you get type1[] being a subtype of type2[] even though type1 is not a subtype of type2.
Avoid trying to put Lists into arrays; put them into Lists.You may be able to miss out the word Integer from that instantiation.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:

The assignment should use ArrayList<List<Integer>> (or shorter, just ArrayList<>). You can still put LinkedLists inside it though.
 
Campbell Ritchie
Marshal
Posts: 56533
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you are right there, Rob. Thank you.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
Scott Shipp
Ranch Hand
Posts: 223
12
Eclipse IDE IntelliJ IDE Java Scala Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
LOL! Liar! Nice class name!

If you really want to dance on the wild side you can just forget about parameterizing it at all.



The compiler also accepts "<Object>" as its type parameter.

As mentioned above, either seems like a bad idea when you can have a list of lists.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!