2

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?

1
  • Why? Sounds more like a class to me than an array. Commented Sep 12, 2010 at 8:40

3 Answers 3

2

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.

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

1 Comment

Or just use Map<Integer, Double[]>.
2

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.

Comments

1

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;
}

1 Comment

actually, why not just use double[] all the way, and cast the first element?

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.