0

I'm trying to create an array of ListNode<String> in Java. I get this error: "cannot create a generic array of ListNode<String> [] when I try to create the array as such:

ListNode<String> [] array = new ListNode<String> [4];

But when I create it like this:

ListNode<String> [] array;

I get an error further down when I try to set spots in the array. For example:

array[0]=start;
array[1]=start2;

Gives me the error "The local variable array may not have been initialized."

How do I fix this? Sorry if this is a basic question! I am in high school.

assylias
  • 321,522
  • 82
  • 660
  • 783
Sarah
  • 1
  • 4
  • http://stackoverflow.com/questions/5662394/java-1-6-creating-an-array-of-listt – assylias Feb 28 '15 at 18:44
  • When I initialize it the way I did in the first case, it gives me the error "You cannot create a generic array of ListNode." – Sarah Feb 28 '15 at 18:45

1 Answers1

0

You can't initialize a ListNode<String>[] because Java simply doesn't allow generic arrays. In your second snippet, you don't initialize the array, so you can't use it.

To solve this, you'll want to use a list instead of an array:

List<ListNode<String>> list = new ArrayList<>();
//....
list.add(start);
list.add(start2);
DennisW
  • 1,057
  • 1
  • 8
  • 17