简体   繁体   English

如何从Object转换为Double []

[英]How to convert from Object to Double[]

I have an object in Java 8 that is really an object array contaning Double objects. 我在Java 8中有一个对象,它实际上是一个包含Double对象的对象数组。 I need to check (using instanceof) and get the values. 我需要检查(使用instanceof)并获取值。 But I always get an error trying to convert to Object[] or Double[]. 但是我总是在尝试转换为Object []或Double []时遇到错误。

This is the variable in Eclipse expressions 这是Eclipse表达式中的变量

在此处输入图片说明

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; java.lang.ClassCastException:无法将java.util.ArrayList强制转换为[Ljava.lang.Object;

But it works on ideone.com: 但它在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. whitelist.get("code").get("position")显然返回一个包含Double对象的ArrayList

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的类型是ArrayList,所以我应该强制转换为该类型并检查该类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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