views:

93

answers:

3

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?

+2  A: 

You can have an array of Objects, 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.

Carlos
+2  A: 

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.

Brian Agnew
Or just use Map<Integer, Double[]>.
Carlos
A: 

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;
}
Thomas Mueller
actually, why not just use double[] all the way, and cast the first element?
Thomas Mueller