简体   繁体   中英

How to cast an array to an array with another primitive type

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM