Reputation: 68907
Can someone complete the code on an easy way?
float[] floats = {...}; // create an array
// Now I want to create a new array of ints from the arrays floats
int[] ints = ????;
I know I can simply cast element by element to a new array. But is it possible on an easier way?
Thanks
Upvotes: 3
Views: 5168
Reputation: 3550
I'm pretty sure you can't do it any other way for your float to int example than individually casting each and every element.
I quickly Googled this which turned up somebody with a similar problem that more or less corroborates what I've said:
http://www.java-forums.org/advanced-java/11255-type-casting-array.html
I would recommend just individually casting the elements. It's guaranteed to work and be easy to understand for a future developer. Any sort of "cast all at once" code would probably just be doing that behind the scenes anyway.
Upvotes: 4
Reputation: 311
You cannot do this directly. Based on the context of how this array is created in used, you may want to consider using an array of a wrapper class, where your setter accepts a float and getter returns an int.
This would be ideal, if it is practical in your situation, because you get to hide the conversion from the client code.
Upvotes: 0