1

I have setter method:

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

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

So, what's wrong?

user207421
  • 305,947
  • 44
  • 307
  • 483
Mr Jedi
  • 33,658
  • 8
  • 30
  • 40

2 Answers2

7

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.

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

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

this.values = Doubles.toArray(Ints.asList(values));
Iulian Popescu
  • 2,595
  • 4
  • 23
  • 31
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
3

You can't mass-cast an entire array across primitives. You need to cast when retrieving the array or convert it element by element:

for(int i=0; i<values.length; i++){
    this.values[i] = values[i]; //int-to-double cast implicit
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117