Reputation: 109
I wrote below code. It get this message:
Exception in thread "main" java.lang.ClassCastException: [D cannot be cast to java.lang.Double
double[] xyz = {1, 11, 111, 2, 22, 222};
ArrayList array = new ArrayList();
array.add(xyz);
double[] vals = new double[array.size()];
vals[0] = (double) array.get(0);
vals[1] = (double) array.get(1);
vals[2] = (double) array.get(2);
I have also search and see some post on Stack Overflow, but they do not make much me sense. What should I do?
Upvotes: 0
Views: 7752
Reputation: 69349
If you want to add an array of double
values to an ArrayList, do this:
Double[] xyz = {...};
ArrayList<Double> array = new ArrayList<>(); // note, use a generic list
array.addAll(Arrays.asList(xyz));
A List
cannot store primitives, so you must store Double
values not double
. If you have an existing double[]
variable, you can use ArrayUtils.toObject()
to convert it.
Upvotes: 6
Reputation: 148
Actually your problem is that you are trying to cast the type of 'xyz', which does not seems to be a double or the Wrapper associed (Double), into a double.
Since java can't transform the type of 'xyz' into a double a ClassCastException is throw. You should try to add n double to your array like that (or even in a loop) :
ArrayList<Double> myListOfDouble = new ArrayList();
myListOfDouble.add(1.0);
And then using a for loop to populate your double[] vals like this :
for(int i = 0; i < myListOfDouble.size(); i++)
vals[i] = myListOfDouble.get(i);
Upvotes: 4