ArrayList中到对象[] [] [英] ArrayList to Object[][]
问题描述
我需要转换一个数组列表为Object [] [],我曾尝试几种不同的方法,并且似乎都折腾了一个或两个错误。
I need to convert an Array List to Object[][], I have tried several different methods, and all seem to toss up an error or two.
我最新的尝试是这样的:
My latest try is this:
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)
我的数组列表中填充了我做了班,这是类:
My array list is populated with classes I made, this is the class:
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;
}
}
这是我如何初始化我数组列表:
This is how I initialize my array list:
public static List<dataClass> dataList = new ArrayList<dataClass>();
我然后通过加入我的新数据类:
I then add my new dataClass via:
.add(new dataClass(...));
任何帮助将是巨大的,谢谢。
Any help would be great, thanks.
推荐答案
您的问题没有完全确定,但这里是我最好的猜测你想要的东西:
Your question is not completely specified, but here's my best guess for what you want:
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的惯用方式书写。
As to whether this is good design or not, without an explanation of what you're trying to accomplish, I can't really comment. This does what I think you want, but the underlying design would give me pause. I would try to understand the objective and then write it in a more Java-idiomatic manner.
这篇关于ArrayList中到对象[] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!