铸造不工作(int []到double []) [英] Casting don't work (int []to double[])

查看:99
本文介绍了铸造不工作(int []到double [])的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有setter方法:

I have setter method:

public void setValues(int[] values){
    this.values = (double[])values;        
}

和Java不允许我这样做。我得到不可逆类型的消息。我知道我可以使用整数和doubleValue()方法,但上面的解决方案应该工作(我想)。

and Java don't allow me to do that. I get message about inconvertible types. I know I can use Integers and doubleValue() method but above solution should work (I think).

那么,有什么问题?

推荐答案

int 转换为 double 而不是从 int [] double [] 。后者不能工作,因为数组是一个对象。所以你有2个不兼容的对象。这个转换肯定会在运行时失败,因此编译器不允许转换,并给你编译器错误。

Casting from int to double is a different thing than casting from int[] to double[]. The later cannot work, because an array is an object. So you have 2 incompatible objects. The cast will surely fail at runtime, and hence compiler doesn't allow the cast, and gives you compiler error.

不幸的是没有直接的方式从 int [] double [] 。您必须为此编写循环。

Unfortunately there is no direct way to convert from int[] to double[]. You have to write loop for that.

for (int i = 0; i < values.length; ++i) {
    this.values[i] = values[i];
}

或者,如果您可以使用 Guava ,您可以使用 Doubles.toArray 方法:

Or, if you can use Guava, you can use Doubles.toArray method:

this.values = Doubles.toArray(Ints.asList(values));

这篇关于铸造不工作(int []到double [])的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆