3

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

2
  • 1
    I think you have to write a loop, and it's maddening that the Java "for ... in" construct is so weak that you can't even use it here in this common scenario. Commented Apr 14, 2010 at 18:08
  • Theoretically, you could create a java.lang.Number-Array, add integers to it and use .floatValue and .intValue as you need it. Commented Apr 14, 2010 at 18:26

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Good to know. I removed the incorrect statement from my answer.
"Any sort of "cast all at once" code would probably just be doing that behind the scenes anyway." Actually, it could use native SSE/AVX for much higher performance, just like System.arraycopy(). Strange that Java doesn't have such a method.
I've searched extensively on the topic of array casting in Java, in order to cast primitive array types to bytes so they can be dumped to a file. Being a C programmer, I was pretty shocked to realize there's no easy way to do it without a for loop. The only alternative I found was starting with a ByteBuffer, and then creating my array (e.g. float[]) as a view into the ByteBuffer, e.g. bb.asFloatBuffer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.