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?
-
Why? Sounds more like a class to me than an array.user207421– user2074212010-09-12 08:40:04 +00:00Commented Sep 12, 2010 at 8:40
3 Answers
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 Doubles, 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 Doubles.
1 Comment
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;
}