我已经查看了几个答案,但发现我找到的答案有误。我正在尝试将 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[])
最佳答案
问题
- First of all,
ec
here is of typeArrayList<Double[]>
, which meansec.get(i)
should returnDouble[]
and notArrayList<Double>
.- Second,
double
andDouble
are completely different types. You can't simply userow.toArray(new double[row.size()])
on your code.
解决方案
1.
如果你想要一个真正的 2D ArrayList
的 Doubles
然后是 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/