views:

138

answers:

3

Out of curiosity, how many dimensions of an array can you have in java.

+2  A: 

I'm not aware of a restriction - as many as you need.

This seems to me to be a good time to be an experimentalist. Why don't you try it, find out what the answer is, and report it back? It's your first opportunity to give something back to the community.

duffymo
"I don't know, why don't you try it and see" is better as a comment, rather than as an answer.
Gabe
I'm not aware seemed like a good enough response. But I do agree that KennyTM has the right answer. I'll probably delete this.
duffymo
+5  A: 

In some ways, you should view every array is single-dimensional. A "multi-dimensional" array in Java such as string[][] is really just an array where the element type is also an array.

I don't know of any limits as to how far that can go - "beyond what's sensible" I suspect. In other words, whatever limit there is, you're unlikely to ever run into it.

Jon Skeet
+14  A: 

The Java language does not limit the number of dimensions, but the Java VM spec limits the number of dimensions to 255.

Proof of concept: http://www.ideone.com/vxkz3

(Ref: http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#1221 "An array type descriptor is valid only if it represents 255 or fewer dimensions.")

KennyTM
In other words, if you needed more than 255 (ha!), you would have to make the outer ones just arrays of objects and then cast them to the actual type once you got below 256.
Gabe
This is interesting - I didn't know that. On one hand, I'm wondering why anyone would ever want to use an array of that dimensionality, and on the other, I'm wondering why they'd limit it like that.
Cam
@Cam 255 fits in 8 bits.
KennyTM
@KennyTM: Well obviously. But if your array has 255+ dimensions, are you really worried about whether it's going to take 8 or 32 bits to store your array's dimensionality?
Cam
I for one can't wait to take advantage of java.util.BigArray for n-dimension arrays. "255 dimensions ought to be enough for anybody." indeed.
RD
@Cam but if you use a 32-bit value to store the number of dimensions, then it will take 32 bits even if you're just having 1D arrays.
KennyTM
@KennyTM: Not necessarily - a flag could be used at the beginning to show whether 32 or 8 bits are being used to store the number of dimensions.
Cam
@Cam it doesn't worth the complexity for something that's extremely rarely used.
KennyTM