0

Here I have

class x{
    ArrayList<Double> values;
    x() {
        values= new ArrayList<Double>();
    }

//here I want to write a method to convert my arraylis(values) in class(x) into an array to be able to use it in my program. Is there any way to do that. thx for your help.

public double [] getarray(){

} 
1

4 Answers 4

2

You shouldn't really need to turn an ArrayList to an array, but if you do, here's how.

public double [] getArray(){
    double[] array = new double[values.size()];
    for(int i =0;i<values.size();i++)
    {
        array[i] = values.get(i) != null ?values.get(i):  0.0;
    }
    return array;
} 
4
  • Or better yet, just use ArrayList.toArray() ;)
    – Andres F.
    Commented Apr 21, 2012 at 21:16
  • .toArray() doesn't convert an ArrayList of Double into an array of the primitive double type.
    – Jonathan
    Commented Apr 21, 2012 at 21:20
  • Ouch! You're right. Maybe a Double[] is equally useful for the OP, though.
    – Andres F.
    Commented Apr 21, 2012 at 21:28
  • 1
    This will throw a NullPointerException if any of the elements is null. Commented Apr 21, 2012 at 21:45
1

Your array list have a toArray() method. Try using that one like:

public double [] getarray(){
    return values.toArray();
} 
2
  • @user1348759 What do you mean "it does not work"? It does work.
    – Andres F.
    Commented Apr 21, 2012 at 21:15
  • It's true toArray() doesn't convert to an array of double[]. But it does convert to Double[], is that useful to you?
    – Andres F.
    Commented Apr 21, 2012 at 21:30
1

With a little help of Apache Commons Lang (see: ArrayUtils.toPrimitive()):

final ArrayList<Double> objList = new ArrayList<Double>();
final Double[] objArray = objList.toArray(new Double[objList.size()]);
final double[] primArray = ArrayUtils.toPrimitive(objArray);
0

If the problem is converting it to a primitive double[], and you can use Guava, then double[] Doubles.toArray(Collection<Double>) does the job just fine. (Disclosure: I contribute to Guava.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.