-2

I have an Arraylist that I want to convert it into an array. I am using this:

double[] array = new double[list.size()];
double [] array = list.toArray(new double[list.size()]);

but, it does not work. Any idea how I can fix it? Thanks in advance. It seems it returns object.

MTT
  • 5,113
  • 7
  • 35
  • 61

6 Answers6

4

For converting a List<Double> to a double[], or anything where you need the primitive type, there's no alternative to doing a traditional for loop (or calling a third-party library method that does a traditional for loop, such as Guava's Doubles.toArray).

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

Alternately, you could do

Double[] array = list.toArray(new Double[list.size()]);

which would get you the array of boxed Doubles, which might suffice for your purposes anyway.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
3

A List can't contain primitive types. Assuming it contains instances of Double, the only way is to iterate over the list and unbox each element (hoping there's no null in the list):

double[] array = new double[list.size()];
int i = 0;
for (Double d : list) {
    array[i] = d;
    i++;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

It should be:

Double[] array = new Double[list.size()];
list.toArray(array); // fill the array

and if you want an array of primitives, iterate over each element in the array:

double[] array = new double[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i).doubleValue();
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

Please read the java docs:

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html

HTH.

John Brown
  • 189
  • 1
  • 7
0

Use the Object Double not the primitive double:

ArrayList<Double> list = new ArrayList<Double>();
...add data
Double[] array=list.toArray(new Double[list.size()]);
bluevoid
  • 1,274
  • 13
  • 29
  • I doubt that is what the goal of the asker is.. They probably want to perform operations on those `doubles` as primitives. – Nora Powers Apr 02 '13 at 20:02
-1
       StringBuffer strBuffer = new StringBuffer();
        for(Object o:list){
            strBuffer.append(o);
        }
        double []x = new double[]{strBuffer.toString()};

I consider this should work

  • 1
    This answer does not work. This is the same as your [other answer here](http://stackoverflow.com/a/16336520/922184). Please make sure your answers actually work before you post them. – Mysticial May 03 '13 at 08:20