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;
} 
Sign up to request clarification or add additional context in comments.

4 Comments

Or better yet, just use ArrayList.toArray() ;)
.toArray() doesn't convert an ArrayList of Double into an array of the primitive double type.
Ouch! You're right. Maybe a Double[] is equally useful for the OP, though.
This will throw a NullPointerException if any of the elements is null.
1

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

public double [] getarray(){
    return values.toArray();
} 

2 Comments

@user1348759 What do you mean "it does not work"? It does work.
It's true toArray() doesn't convert to an array of double[]. But it does convert to Double[], is that useful to you?
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);

Comments

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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.