java-将2D ArrayList转换为2D Array
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java-将2D ArrayList转换为2D Array,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2201字,纯文字阅读大概需要4分钟。
内容图文
![java-将2D ArrayList转换为2D Array](/upload/InfoBanner/zyjiaocheng/691/c2f32deb1f344496a3ba692a2ec7c1cf.jpg)
我已经查看了几个答案,但发现的答案却有误.我正在尝试将Doubles []的ArrayList转换为普通的double 2D数组.我的代码:
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.
如果您想要真正的Double的2D ArrayList,则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-将2D ArrayList转换为2D Array全部内容,希望文章能够帮你解决java-将2D ArrayList转换为2D Array所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。