This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic List array

 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
I want a String list array, which I am trying to create using the statement:
List<String>[] listArray = new List<String>[3];
But the compiler is giving an error for 'new List<String>[3]'. If I use the statement:
List<String>[] listArray = new List[3];
it works fine. But I am not sure if it serves my purpose. Can anyone please clarify?

Thanks,
Ganesh
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15356
39
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot create an array with elements of concrete parameterized type. The reason for this is quite technical (because generics in Java are implemented with type erasure, which is incompatible with how arrays work).

See my blog post for details.
 
Rekha Srinath
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all, Ganesh, I do not get how List<String>[] listArray = new List[3]; is correct, because List is an interface and how can we do a "new" on it?
 
Vlado Zajac
Ranch Hand
Posts: 245
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

does not do new on List, but on List[].


or

would be incorrect because List is interface.

[ October 02, 2008: Message edited by: Vlado Zajac ]

[ October 02, 2008: Message edited by: Vlado Zajac ]
[ October 02, 2008: Message edited by: Vlado Zajac ]
 
Vijitha Kumara
Bartender
Posts: 3913
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper Young
------------
See my blog post for details.


That's a really good one.
[ October 15, 2008: Message edited by: Vijitha Kumara ]
 
Mohammad Khan
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
// Following code my help to understand the issue you are having.

interface MyInterface {};
class MyClass implements MyInterface {};


public class MyApp {

public static void main(String[] args) {
MyInterface myInterface;

// You can't instantiate an interface, so following code would failed duing compile
//myInterface = new MyInterface();

// But you can do this, as MyClass IS-A MyInterface
myInterface = new MyClass();

// For more information about List, take a look at
// http://java.sun.com/javase/6/docs/api/java/util/List.html
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic