[英]Converting Scala List[List[Double]] to Java double[][]
[英]Converting a List to Double[][]
使用下面的代碼,我試圖將Doubles列表轉換為Double [] []。 但是在方法上: Double[][] dim = list1.toArray(new Double[2][2]);
我收到此錯誤:
Exception in thread "main" java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.ArrayList.toArray(ArrayList.java:361)
at clustering.main.ConvertArrayTest.main(ConvertArrayTest.java:22)
該行發生錯誤:
Double[][] dim = list1.toArray(new Double[2][2]);
我如何無法正確轉換列表?
編碼 :
import java.util.ArrayList;
import java.util.List;
public class ConvertArrayTest {
public static void main(String args[]){
List<ArrayList<Double>> list1 = new ArrayList<ArrayList<Double>>();
ArrayList<Double> list2 = new ArrayList<Double>();
list2.add(1.0);
list2.add(1.0);
list1.add(list2);
list2 = new ArrayList<Double>();
list2.add(2.0);
list2.add(2.0);
list1.add(list2);
Double[][] dim = list1.toArray(new Double[2][2]);
}
}
因為list1
是一個列表列表,所以當您調用toArray
,您將獲得一個列表數組。 您需要遍歷它,分別轉換每個內部列表。
固定主方法在這里:
public static void main(String args[]){
List<ArrayList<Double>> list1 = new ArrayList<ArrayList<Double>>();
ArrayList<Double> list2 = new ArrayList<Double>();
list2.add(1.0);
list2.add(1.0);
list1.add(list2);
list2 = new ArrayList<Double>();
list2.add(2.0);
list2.add(2.0);
list1.add(list2);
Double[][] dim = new Double[2][2];
int i = 0;
for(ArrayList<Double> inner : list1)
dim[i++] = inner.toArray(new Double[0]);
}
您的第一個列表是數組列表的列表,因此您需要對其進行迭代。
我可能會創建這樣的方法-
public static Double[][] toDoubleArrayArray(
List<ArrayList<Double>> al) {
if (al == null) { // return null on null.
return null;
}
Double[][] ret = new Double[al.size()][]; // declare the return array array.
for (int i = 0; i < al.size(); i++) {
ArrayList<Double> list = al.get(i); // get the inner list.
if (list == null) { // handle null.
ret[i] = null;
} else {
Double[] inner = new Double[list.size()]; // make the inner list an array.
ret[i] = list.toArray(inner); // store that array.
}
}
return ret; // return
}
然后我像這樣測試
public static void main(String[] args) {
List<ArrayList<Double>> list1 = new ArrayList<ArrayList<Double>>();
list1.add(new ArrayList<Double>(Arrays.asList(1.0, 1.0)));
list1.add(new ArrayList<Double>(Arrays.asList(2.0, 2.0)));
Double[][] arr = toDoubleArrayArray(list1);
for (int i = 0; i < arr.length; i++) {
System.out.println(Arrays.toString(arr[i]));
}
}
哪個輸出預期
[1.0, 1.0]
[2.0, 2.0]
使用這種方式:
代碼 :
public static void main(String[] args) {
List<Double[]> list = new ArrayList<Double[]>();
list.add(new Double[] { 1.0 });
list.add(new Double[] { 2.0, 2.0 });
list.add(new Double[] { 3.0, 3.0, 3.0 });
Double[][] array = list.toArray(new Double[list.size()][]);
for (Double[] numbers : array) {
System.out.println(Arrays.toString(numbers));
}
}
輸出 :
[1.0]
[2.0, 2.0]
[3.0, 3.0, 3.0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.