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;
0

3 Answers 3

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.

2
  • That gives an Object[] instead of an Object[][] according to Netbeans
    – jobukkit
    Commented Jun 16, 2013 at 17:16
  • @com.BOY It looks like you've got a non-generic list then - you need to add a cast. Commented Jun 16, 2013 at 17:17
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);
}
2
  • Instead of the second for loop, you can use System.arraycopy(array, 0, output[i], 0, array.length);
    – BackSlash
    Commented Jun 16, 2013 at 16:56
  • @BackSlash yes, that's nicer. Edited! Commented Jun 16, 2013 at 16:59
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();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.