2014-10-28 85 views
0

我需要将数组列表转换为对象[] [],我尝试了几种不同的方法,并且都似乎抛出了一两个错误。ArrayList to Object [] []

我最新的尝试是这样的:

Object[][] array = dataList.toArray(new Object[dataList.size()][]); 

这引发以下错误:

java.lang.ArrayStoreException 
    at java.lang.System.arraycopy(Native Method) 
    at java.util.ArrayList.toArray(Unknown Source) 

我的数组列表中填充了我发班,这是类:

class dataClass { 
    int x; 
    int y; 
    int z; 
    String string1; 
    String string2; 
    Date date; 
    int event; 

    public dataClass(int x, int y, int z, String string1, String string2, 
      Date date, int event) { 
     this.x = x; 
     this.y = y; 
     this.z = z; 
     this.string1 = string1; 
     this.string2 = string2; 
     this.date = date; 
     this.event = event; 
    } 
} 

这是我如何初始化我的数组列表:

public static List<dataClass> dataList = new ArrayList<dataClass>(); 

我然后通过添加我的新数据类:

.add(new dataClass(...)); 

任何帮助将是巨大的,谢谢。

+3

您如何期待ArrayList中的元素存储在Object [] []中? – 2014-10-28 00:03:33

+8

我看到一个额外的维度没有明显的原因冒出来,你能详细说明吗? – Jack 2014-10-28 00:03:51

+10

平地人民需要一个答案 – tom 2014-10-28 00:04:29

回答

1

你的问题没有完全确定,但这里是我最好的猜测你想要的东西:

Object[][] array = new Object[dataList.size()][]; 
int i = 0; 
for (DataClass c : dataList) 
{ 
    array[i] = new Object[7]; 
    array[i][0] = c.x; 
    array[i][1] = c.y; 
    array[i][2] = c.z; 
    array[i][3] = c.string1; 
    array[i][4] = c.string2; 
    array[i][5] = c.date; 
    array[i][6] = c.event; 
    i++; 
} 

至于这是否是好的设计或没有,没有,你要完成什么样的解释,我无法评论。这就是我想要的,但底层设计会让我停下来。我会试着去理解这个目标,然后用更加Java的惯用方式来写它。

1

你有包含dataClass对象的arraylist。您可以将其转换为一维数组而不是二维数组。

dataClass [] dataArr = dataList.toArray(new dataClass [dataList.size()]);