简体   繁体   English

如何将整数的ArrayList转换为double []?

[英]How do I convert an ArrayList of integers to a double[]?

I have set up the following ArrayList: 我设置了以下ArrayList:

ArrayList<Integer> myIntegerValues = new ArrayList<Integer>();
myIntegerValues.add(0);
myIntegerValues.add(1);
myIntegerValues.add(0);
myIntegerValues.add(1);

I want to convert this to a double[] and run a simple piece of code like this 我想将其转换为double[]并运行像这样的简单代码

double[] myList = {1.9, 2.9, 3.4, 3.5, 2.9, 3.8, 10.2};        
for (int i = 0; i < myList.length; i++) {
    System.out.println(myList[i] + " ");
}

How do I convert an ArrayList to a double[] ? 如何将ArrayList转换为double[]

I found this link How to cast from List<Double> to double[] in Java? 我发现此链接如何在Java中从List <Double>转换为double []? but I'm not sure if this answers my question or not. 但我不确定这是否能回答我的问题。

double[] array = myIntegerValues.stream().mapToDouble(i -> (double) i).toArray();

Declare a double arry of the size of the arraylist first, since arrays aren't dynamic. 由于数组不是动态的,因此请首先声明arraylist大小的两倍。

double[] doublesList = new double[myIntegerValues.size()];

then loop through and convert each one 然后遍历并转换每个

int x = 0;
for(Integer i : myIntegerValues){
    doublesList[x] = (double)i;
    x++;
}

Best thing to do is to create an array of matching size and then iterate over the entries, casting as you go. 最好的办法是创建一个匹配大小的数组,然后遍历所有条目,然后进行转换。

double[] myList = new double[myIntegerValues.size()];
for (int i=0; i<myIntegerValues.size(); i++) {
   myList[i] = (double) myIntegerValues.get(i);
}

Note, while I could use an iterator, using indexes makes the one to one relationship clear. 注意,虽然我可以使用迭代器,但使用索引可以使一对一关系变得清晰。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM