Search code examples
javaclasscastexception

How to convert from Object to Double[]


I have an object in Java 8 that is really an object array contaning Double objects. I need to check (using instanceof) and get the values. But I always get an error trying to convert to Object[] or Double[].

This is the variable in Eclipse expressions

enter image description here

I get this exception when running the code

Object position = whitelist.get("code").get("position");
if(position!=null){
     feature.setGeometry(new Point(((Double []) position)[0],((Double []) position)[1]));
}

java.lang.ClassCastException: java.util.ArrayList cannot be cast to [Ljava.lang.Object;

But it works on ideone.com:

<script src="http://ideone.com/e.js/J2ZJSV" type="text/javascript" ></script>

Edit: my own answer...


Solution

  • whitelist.get("code").get("position") apparently returns an ArrayList containing Double objects.

    You can therefore simply write:

    List<Double> position = (List<Double>)whitelist.get("code").get("position");
    if (position!=null)
         feature.setGeometry(new Point(position.get(0),position.get(1)));