2

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(",")));
2
  • What type of values should be in ArrayList list? Are they doubles? For the sake of clarity, can you provide a code snippet which uses your convert function? Commented Jun 9, 2015 at 19:12
  • I provided the piece of code, it reads from a file and saves the integers to an arraylist. Commented Jun 9, 2015 at 19:21

5 Answers 5

2

use this:

array[x]=Double.parseDouble(list.get(x));
Sign up to request clarification or add additional context in comments.

3 Comments

How this will compile? Double.parseDouble takes String argument. list.get(x) returns Object.
this convert string to double
this line to convert string to double in correct way to avoid String cannot be cast to java.lang.Double, so I tried to change code and fix it
1

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

Comments

0

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

    }
}

Comments

0

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

Comments

0

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);
        }

    }    
}

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.