简体   繁体   中英

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

I have set up the following 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[] 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[] ?

I found this link How to cast from List<Double> to double[] in Java? 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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