java - 将二维 ArrayList 转换为二维数组

标签 java arrays arraylist

我已经查看了几个答案,但发现我找到的答案有误。我正在尝试将 Doubles[] 的 ArrayList 转换为普通的 double 二维数组。我的代码:

    public ArrayList<Double[]>  ec;
    public double[][]           ei;
    ...
    encogCorpus = new ArrayList<Double[]>();
    ...
    ec.add(inputs);
    ...
    ei = new double[ec.size()][];

    for (int i = 0; i < ec.size(); i++) {
        ArrayList<Double> row = ec.get(i);
        ei[i] = row.toArray(new double[row.size()]);
    }

我收到错误提示

Type mismatch: cannot convert from Double[] to ArrayList

The method toArray(T[]) in the type ArrayList is not applicable for the arguments (double[])

最佳答案

问题

  1. First of all, ec here is of type ArrayList<Double[]>, which means ec.get(i) should return Double[] and not ArrayList<Double>.
  2. Second, double and Double are completely different types. You can't simply use row.toArray(new double[row.size()]) on your code.

解决方案

1.

如果你想要一个真正的 2D ArrayListDoubles然后是 ec 的类型应该是 ArrayList<ArrayList<Double>> .但是因为我们不能使用toArray() ,我们改为手动循环。

public ArrayList<ArrayList<Double>> ec;  // line changed here
public double[][]                   ei;
...
encogCorpus = new ArrayList<ArrayList<Double>>(); // and here also
...
ec.add(inputs); // `inputs` here should be of type `ArrayList<Double>`
...
ei = new double[ec.size()][];

for (int i = 0; i < ec.size(); i++) {
    ArrayList<Double> row = ec.get(i);

    // Perform equivalent `toArray` operation
    double[] copy = new double[row.size()];
    for (int j = 0; j < row.size(); j++) {
        // Manually loop and set individually
        copy[j] = row.get(j);
    }

    ei[i] = copy;
}

2.

但是如果你坚持使用ArrayList<Double[]> ,我们只需要改变主要部分:

public ArrayList<Double[]>  ec;
public double[][]           ei;
...
encogCorpus = new ArrayList<Double[]>();
...
ec.add(inputs);
...
ei = new double[ec.size()][];

for (int i = 0; i < ec.size(); i++) {
    // Changes are only below here

    Double[] row = ec.get(i);
    double[] copy = new double[row.length];

    // Still, manually loop...
    for (int j = 0; j < row.length; j++) {
        copy[j] = row[j];
    }

    ei[i] = copy;
}

3.

最后,如果你能改变Double[]double[] , 解 2 会变成,

public ArrayList<double[]>  ec; // Changed type
public double[][]           ei;
...
...
for (int i = 0; i < ec.size(); i++) {
    // Simpler changes here
    ei[i] = ec.get(i).clone();
}
...

关于java - 将二维 ArrayList 转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31522416/

相关文章:

arrays - 为什么我的调试器在字符数组中显示额外的字符?

Java 将 ObjectInputStream 结果转换为 ArrayList

java - ArrayList 和添加项的问题

java - 保持枚举在数组列表中排序?

java - 如何在 Java 中比较字符串?

java - 未获取 Firebase 数据库数据

java - 面板不会显示文本

java - 使用 Java 从 XSL-FO 生成 HTML

javascript - 从数组中提取随机字符串并插入句子

arrays - 如何为已打乱的数组添加依赖项?