开发者

can I use float[] to hold ints?

we have one class which has one float[] and one int[]. Sometimes the user of that class needs put float valuse and sometimes int values, but will not be both for each instance.

We know all the possilbe float and int values will not be big (less than 100000). I am thinking we may not need the int[], just use the float[] to hold int values when necessary. At the time we use them, we can cast them to int when necessary. One storage array will be much开发者_开发技巧 clear.

How do you think about my idea? put int into float[] will not lose anything. I am right?

EDIT:

One class have one float[] class variable and one int[] class variable to hold values for user. Users of that will use either float[] or int[] but not both. So we have get float[]and set float[] methods, AND get int[] and set int[] methods, and different constructors. I am thinking to simplify this class by remove int[] class variable and use a float[] for both int values and float values for different users.


float has 24 bits of precision (and a sign bit) which means you can store int values between -16777216 to 16777216 without loss of precision.

If all your values are even or multiples of 10 or 100 you can store larger values safely. The important thing is that your numbers when divided by all their powers of two must be within the range.

To combine int and float I would use double which can hold all possible float and int values. The extra memory this consumes is unlikely to be significant. (Unless you have millions of these)


For values less than 100,000 that should be fine. Not all int values can be represented exactly as float (they're both 32 bit data types, after all), but in that range you should be okay.

I'm not really sure it's a great idea, mind you, but it should work.


Three separate answers, depending on your use case:

  1. If you need to expose the actual int array or float array, make your member variable an Object, and cast to int[] or float[] as needed.

  2. If you are not interested in space efficiency, use generics and ArrayList<T> where T is Integer or Float

  3. If you want to be masochistic, (and don't need to expose the actual array) you can use just an int[], then use Float.floatToRawIntBits() and Float.intBitsToFloat(int) to convert a float to four bytes stored as an int and vice-versa, respectively.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜