How to cast an array to an array with another primitive type
Can someone complete the code on an easy way?
float[] floats = {...}; // cre开发者_StackOverflow中文版ate 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
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.
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.
精彩评论