铸造不工作(int []到double []) [英] Casting don't work (int []to 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屋!