0

I want to store 4 Lists of Strings to an array within index 0-3 and be able to check wether the index is filled (!=null) or not.

For that reason I need to initialize an Array of Type List, which fails in eclipse with message "Cannot create a generic array of List":

// Does not work
List<String>[] myArray = new List<String>[4];

// Does not work
List<String>[] myArray = new ArrayList<String>[4];

Doing it like promoted at Convert an ArrayList to an object array :

ArrayList<List<String>> myArrayList = new ArrayList<List<String>>();
myArrayList.add(new ArrayList<String>());
myArrayList.add(new ArrayList<String>());
myArrayList.add(new ArrayList<String>());
myArrayList.add(new ArrayList<String>());

// Does not work
List<String>[] myArray = myArrayList.toArray(new List<String>[myArrayList.size()]);

// Does not work
List<String>[] myArray = myArrayList.toArray(new ArrayList<String [myArrayList.size()]);

But why is this not working?

7
  • possible duplicate of Initialize an Array of ArrayList Commented Jan 21, 2014 at 13:47
  • 1
    Because "you cannot create a generic array" in Java. This was a design choice which has to do with the mismatch between the reifiability of array types vs. non-reifiability of generic type parameters. Commented Jan 21, 2014 at 13:47
  • 2
    only Cuck Norris can initiate Interfaces: new List<String>[myArrayList.size()]!!! :-) Commented Jan 21, 2014 at 13:47
  • @StefanBeike There's nothing wrong with an array of interface type: List[]. Commented Jan 21, 2014 at 13:48
  • @Marko Topolnik: with "new List" I am able to create a List object??? Commented Jan 21, 2014 at 13:51

1 Answer 1

0

ArrayList is generic class in Java. You cannot create an array of generic type. It is not allowed. What you can do is create a list of generic type

ArrayList<ArrayList<String>> listOfStringList = new ArrayList<ArrayList<String>>();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer! Despite of this it does not come in my head, why Java is disallowing that.
That is going to be design choice, it causes problems with backward compatibility, type casting issues etc.
Did it help you understand?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.