0

The following code throws an ClassCastException:

ArrayList<V>[] table = (ArrayList<V>[]) new Object[tableSize];

How can I create an Array of ArrayList if this doesn't work?

EDIT:

To be shure everybody understands the problem. I need an Array that contains multiple ArrayLists.

EDIT2:

tableSize is an int.

Raandom
  • 35
  • 3

3 Answers3

-1

EDIT: OK, here is what you can do:

ArrayList<String>[] table = new ArrayList[tableSize];

It compiles and works on Java 8 i'm using.

kajacx
  • 12,361
  • 5
  • 43
  • 70
-1

In case of Java you can not create new instance of array that type is generic.

T[] array = new T[size]; - cause compile error Cannot create a generic array of T.

The same error will be present when you will try to use it

ArrayList<T>[] array = new ArrayList<T>[size];

With the same reason. The Java runtime does not know what is T after compilation therefor will not be able to allocate valid memory space.

To pass this issue you have following options:

  • Remove the generic type and use a raw.

ArrayList[] array =new ArrayList[size];

  • Use list of a list

List<List<T>> list = new ArrayList<List<T>>();

-1

Not the smoothest way to do it But if I got your question correctly something like this should do the trick:

int tableSize = 2;
Collection<String> listWithItems = new ArrayList<>();
listWithItems.add("Foo");
listWithItems.add("Bar");    

Collection<Collection<String>> listOfList = new ArrayList<>();
listOfList.add(listWithItems);    

Object[] array = listOfList.toArray(new Object[tableSize]);    

System.out.println("Col: " + listOfList);
System.out.println("Array: " + Arrays.toString(array));

Print out is:

Col: [[Foo, Bar]]
Array: [[Foo, Bar], null]

Short example without extra "fluff" to get the inital array:

Object[] theArrayOfLists = new ArrayList<List<SomeClass>>().toArray(new Object[tableSize]);
trappski
  • 1,066
  • 10
  • 22