user3778684
user3778684

Reputation: 45

How do I convert List<List<Object>> to a multi-dimensional array?

List<List<Object>> EventAll = new ArrayList<List<Object>>();

while(rs1.next())
{
    List<Object> row = new ArrayList<Object>();
    /*EventAll.add(rs1.getRow(), row);*/
    row.add(rs1.getString("eventName")); 
    row.add(rs1.getString("duration")); 
    row.add(rs1.getString("playhead"));
    EventAll.add(row);
}

String[][] stringArray = EventAll.toArray(new String[EventAll.size()][]);//line 66

In the above example as you can see I have List<List<Object>> and I am adding column values to it in the while loop. It worked fine for me at this point.

But when I tried converting it into multi-dimensional array using toArray() method I am getting the following exception:

****EXCEPTION:**java.lang.ArrayStoreException
    at java.lang.System.arraycopy(Native Method)
    at java.util.ArrayList.toArray(Unknown Source)
    at DataFromMySql.main(DataFromMySql.java:66)**

Upvotes: 0

Views: 1282

Answers (3)

Eran
Eran

Reputation: 393831

toArray can convert your List<List<String>> (you should, BTW, change your List<List<Object>> to List<List<String>>) to List<String>[], not to a String[][].

It can also convert each inner List<String> to a String[].

Therefore, you'll have to create the 2-D array, and initialize each row of that array separately with EventAll.get(i).toArray(new String[EventAll.get(i).size()]).

Upvotes: 2

ParkerHalo
ParkerHalo

Reputation: 4430

Please note that this will only work if your inner Lists do have the same length and all Objects are strings!

String[][] array = new String[list.size()][list.get(0).size()];
System.out.println();
int i = 0;
for (List<Object> l : list ) {
    int j = 0;
    for (Object obj : l) {
        array[i][j] = (String) obj;
        j++;
    }
    i++;
}

Upvotes: 0

SatyaTNV
SatyaTNV

Reputation: 4135

Object[][] array = new Object[EventAll.size()][];

int i = 0;
for (List<Object> event : EventAll) {//each list
    array[i++] = event.toArray(new Object[event.size()]);
}

Upvotes: 2

Related Questions