Java convert ArrayList to int array

967 Views Asked by At

I want to convert my arraylist to a double array[]. Why can't I cast with this method, what is wrong?

public static void convert(ArrayList list, double array[]) {



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

    for (int x = 0; x < list.size(); x++) {

        array[x]=(double) list.get(x);

    }

}

I get this error message

String cannot be cast to java.lang.Double

I have this peace of code that does not work if I change fropm raw type ArrayList to Double, maybe suggestions to change this code?

getTest().addAll(Arrays.asList(line.split(",")));
5

There are 5 best solutions below

0
On

Exception message says it - your ArrayList contains String values. You should use generics as ArrayList<String> to prevent this runtime failures

3
On

use this:

array[x]=Double.parseDouble(list.get(x));
0
On

You can not apply casting on String to make it double like this -

array[x]=(double) list.get(x); 

Your list is an ArrayList of Stirng. So you have to convert the each String item from the list to double like this -

public static void convert(ArrayList list, double array[]) {

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

    for (int x = 0; x < list.size(); x++) {

       array[x]=Double.parseDouble((String)list.get(x));

    }
}
0
On

Ive got the idea. I just convert my ArrayList to ArrayList Then your code examples will work same as mine...

0
On

Use this code:

public static void convert(ArrayList list, double array[]) {

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

    for (int x = 0; x < list.size(); x++) 
    {
        Object value = list.get(x);
        if(value instanceof String)
        {
            array[x]=Double.parseDouble(value.toString());
        }
        else if(value instanceof Double)
        {
             array[x]=(double) list.get(x);
        }
        else if(value instanceof Integer)
        {
             array[x]=(int) list.get(x);
        }

    }    
}