简体   繁体   中英

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

在此处输入图片说明

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM