views:

161

answers:

2

Hi,

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

+3  A: 

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.

Morinar
Java does not allow casting array types to sub-classes (e.g. `String[] sarray = (String[]) new Object[10];`). Attempting to do this results in a runtime `ClassCastException`.
Kevin Brock
Good to know. I removed the incorrect statement from my answer.
Morinar
A: 

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.

Sean