Domanda

I wanted to dynamically generate an array of fixed sized String[] (String[][] object), filled w. Strings of rows values from db to create JTable.

To do that, I used ArrayList of String[], dynamically filled it up. And then convert it to Array using list.toArray(). But .toArray() only convert the list into single dimension Array either Object[] or T[].

I need String[][] / Object[][] to use the JTable constructor.

The code

Object[][] dlist = (Object[][]) al.toArray();

generates: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [[Ljava.lang.Object;

ers = pdao.getEmployeeResultSet(prs.getInt("PROJ_ID"));
ArrayList<String[]> alist = new ArrayList<String[]>();
while (ers.next()){
    String eid = ers.getString("EMP_ID");
    String ename = ers.getString("EMP_NAME");
    String gend = ers.getString("GENDER");
    String bd = ers.getString("BIRTHDATE");
    String addr = ers.getString("ADDRESS");
    String city = ers.getString("City");

    String[] str = {eid, ename, gend, bd, addr, city};
    alist.add(str);
}
Object[][] dlist = (Object[][]) al.toArray();
String[] cnames = {"EMP_ID","EMP_NAME","GENDER","BIRTHDATE","Address","City"};

jtable = new JTable(dlist, cnames);

I used the tuturial on : http://docs.oracle.com/javase/tutorial/displayCode.html?code=http://docs.oracle.com/javase/tutorial/uiswing/examples/components/SimpleTableDemoProject/src/components/SimpleTableDemo.java to create JTable.

È stato utile?

Soluzione 2

I would just create the double array myself, if you really wanted to:

public static String[][] getDArray(final ArrayList<String[]> aList) {
    final int size = aList.size();
    final String[][] ans = new String[size][];

    for(int i = 0; i < size; ++i)
        ans[i] = aList.get(i);

    return ans;
}

Altri suggerimenti

Simply use

String[][] dlist = alist.toArray(new String[][]{});

The array you pass to the method can alternatively be used as the actual array that will be returned if you know the size (which you do with alist.size()), but it's really useful for the type of array that you want.

You can actually confirm this with

String[][] holder = new String[alist.size()][];
String[][] returned = alist.toArray(holder);
System.out.println(holder == returned);

will print

true

Now, obviously, since arrays are covariant, you can also do

Object[][] dlist = al.toArray(holder);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top