2

I have an ArrayList with Object[]'s and I need to convert the ArrayList into an Object[][] array in order to put the data in a JTable. How can I do this?

I have tried:

(Object[][]) arraylist.toArray();

but that gave:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;
jobukkit
  • 2,490
  • 8
  • 26
  • 41

3 Answers3

5

You can use toArray, like this:

Object[][] array2d = (Object[][])arraylist.toArray(new Object[arraylist.size()][]);

This is a non-generic version; generic toArray(T[] a) lets you avoid the cast.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

Try this, an explicit solution that takes into account arrays with variable lengths:

ArrayList<Object[]> input = new ArrayList<>();
Object[][] output = new Object[input.size()][];

for (int i = 0; i < input.size(); i++) {
    Object[] array = input.get(i);
    output[i] = new Object[array.length];
    System.arraycopy(array, 0, output[i], 0, array.length);
}
Óscar López
  • 232,561
  • 37
  • 312
  • 386
0
    List<Object[]> list = new ArrayList();
    list.add(new Object[]{1,2,3});

    Object[][] objArray = new Object[list.size()][];
    for (int i=0;i<objArray.length;i++)
        objArray[i] = list.get(i).clone();