I have a 2D Double array that is expanding and I am not sure of its final size therefore I want to convert it to a 2d arraylist but not sure how to do this I tried to define the array list first and use addAll(Array) method but it doesn't work. Any suggestion?
我有一个2 d双阵列扩展和它最终大小的我不确定所以我想把它转换成一个2 d arraylist,但是不知道如何做到这一点我想首先定义数组列表并使用addAll(数组)方法,但它不工作。任何建议吗?
I just wrote this code I think it will work fine but I am looking for more efficient way
我刚写了这段代码,我认为它会很好,但是我在寻找更有效的方法。
public class trial {
public static void main(String[] arg){
double[][] Solutions_to_arrange={{1,5,2,8,4,70,50,80},{3,7,4,2,6,60,30,70},{8,1,6,4,2,10,40,60}};
ArrayList<ArrayList<Double>> Solutions_to_arrange_A=new ArrayList<ArrayList<Double>>();
for(int i=0;i<Solutions_to_arrange.length;i++){
Solutions_to_arrange_A.add(new ArrayList<Double>());
for(int j=0;j<Solutions_to_arrange[0].length;j++){
Solutions_to_arrange_A.get(i).add(Solutions_to_arrange[i][j]);
}
}
}
}
Also I have question on putting the statement
我对发表声明也有疑问
Solutions_to_arrange_A.add(new ArrayList<Double>());
Should I put it within the loop or its sufficient to call it just once outside the loop
我应该把它放在循环中还是仅仅在循环外调用一次就足够了
1 个解决方案
#1
4
try it:
试一试:
Double[][] matriz = {{1d,5d,2d,8d,4d,70d,50d,80d},{3d,7d,4d,2d,6d,60d,30d,70d},{8d,1d,6d,4d,2d,10d,40d,60d}};
List<List> result = new ArrayList<>();
for(Double[] array : matriz){
result.add( Arrays.asList(array) );
}
If we use primitive types in "Arrays.asList" we will get a list with one primitive array as its unique item. With object type it will works fine.
如果我们在“数组”中使用原始类型。asList"我们将得到一个具有一个原始数组作为其唯一项的列表。对于对象类型,它可以正常工作。
#1
4
try it:
试一试:
Double[][] matriz = {{1d,5d,2d,8d,4d,70d,50d,80d},{3d,7d,4d,2d,6d,60d,30d,70d},{8d,1d,6d,4d,2d,10d,40d,60d}};
List<List> result = new ArrayList<>();
for(Double[] array : matriz){
result.add( Arrays.asList(array) );
}
If we use primitive types in "Arrays.asList" we will get a list with one primitive array as its unique item. With object type it will works fine.
如果我们在“数组”中使用原始类型。asList"我们将得到一个具有一个原始数组作为其唯一项的列表。对于对象类型,它可以正常工作。