gavioto
gavioto

Reputation: 1745

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...

Upvotes: 0

Views: 201

Answers (2)

gavioto
gavioto

Reputation: 1745

I'm concerned about this error. It's very simple error to solve, but now that I posted here (definitively this is not may best day) I will post also the solution.

The type of the Object is ArrayList, so I should cast to this type and check for this type.

Object position = whitelist.get("code").get("position");
if(position!=null && position instanceof List<?>){
    List<Double> point = (List) position;
    feature.setGeometry(new Point(point.get(0),point.get(1)));
}

Upvotes: 0

wero
wero

Reputation: 33000

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

Upvotes: 1

Related Questions