0

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?

Arash m
  • 99
  • 2
  • 12
  • 2
    possible duplicate of [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Minty Fresh Mar 13 '15 at 14:27
  • 4
    This makes no sense, `array.add(xyz);`. It is of key importance to show us ***exactly*** what you're adding to that ArrayList. You should be using an `ArrayList` regardless. – Hovercraft Full Of Eels Mar 13 '15 at 14:27
  • 3
    It's not `D` but `[D`, ie an array of `double`s. – fge Mar 13 '15 at 14:30
  • @MintyFresh That is not a duplicate, because the questions are not the same. But it is a related question that the OP should read. – Duncan Jones Mar 13 '15 at 15:34

2 Answers2

6

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.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
4

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);
Tom
  • 16,842
  • 17
  • 45
  • 54
damus4
  • 148
  • 2
  • 7