Reputation: 168
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(",")));
Upvotes: 2
Views: 965
Reputation: 224
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);
}
}
}
Upvotes: 0
Reputation: 168
Ive got the idea. I just convert my ArrayList to ArrayList Then your code examples will work same as mine...
Upvotes: 0
Reputation: 11153
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));
}
}
Upvotes: 0
Reputation: 1263
Exception message says it - your ArrayList contains String values. You should use generics as ArrayList<String>
to prevent this runtime failures
Upvotes: 1