gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 20:21:19 25 4
gpt4 key购买 nike

我已经查看了几个答案,但发现我找到的答案有误。我正在尝试将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com