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.

Sign up to request clarification or add additional context in comments.

2 Comments

That gives an Object[] instead of an Object[][] according to Netbeans
@com.BOY It looks like you've got a non-generic list then - you need to add a cast.
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 Comments

Instead of the second for loop, you can use System.arraycopy(array, 0, output[i], 0, array.length);
@BackSlash yes, that's nicer. Edited!
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();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.