【问题标题】:ArrayList to Object[][] [closed]ArrayList 到 Object[][] [关闭]
【发布时间】:2014-10-28 00:02:27
【问题描述】:

我需要将 Array List 转换为 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(...));

任何帮助都会很棒,谢谢。

【问题讨论】:

  • 您希望ArrayList 中的元素如何存储在Object[][] 中?
  • 我看到一个额外的维度突然出现,没有明显的原因,你能详细说明吗?
  • 平原人民需要一个答案
  • 在 Java 中,类名以大写字母开头是惯例。请查看 Java 教程:Variables and Naming
  • @ScubaSteve 我假设dataListjava.util.ArrayList

标签: java arrays object arraylist


【解决方案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 的惯用方式编写它。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-10-03
      • 2014-06-14
      • 2014-07-31
      • 2021-01-14
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多