Is there a way to put an int and a Double in the same array. I want to have an array (p1[]
) where the first (p1[0]
) is an int and all the rest of the elements are doubles. Is this possible?
views:
93answers:
3You can have an array of Object
s, in which case you can put Integer and Double objects in it. However, I doubt there might be a better way to store your data than an array.
EDIT: You should of course make it a Number
array as Nikita suggested.
You can do this by having an array of objects that are superclasses of Integer/Double (as pointed out elsewhere).
However I would perhaps enforce type safety by implementing an object that has an Integer
component plus an array of Double
s, and store an array of these. The upside (despite the additional complexity) is that you'll have type safety and not have to cast the first element to an Integer
whilst casting the remainder to Double
s.
If memory is very important, you might want to use long[] instead. You can store the "int" easily, but the "double" needs more work:
long x = Double.doubleToRawLongBits(double value);
double value = Double.longBitsToDouble(long x).
But maybe it's better to create a special class, and then shift the array index:
class Y {
int x;
double[] values;
}