5

It looks like all java containers, buffers, arrays and etc, can only be indexed by int. On C++, I can index by unsidned long for example.

What is the solution for this in Java? I can surely create my own class that uses lots of int32 indexable buffers and access the rigth one, but is there a better and simpler way?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 1
    No, there isn't -- unless your array is particularly sparse, in which case a `Map` might work. – Louis Wasserman Sep 13 '21 at 19:23
  • 1
    Why do you want to use long to index in Java anyway? It depends on the architecture of the language and I don't think Java can support that big of an index. – Abishek Stephen Sep 13 '21 at 19:27
  • There's no simpler way; it's baked into the JVM. See, for example, https://stackoverflow.com/q/3038392/438992, which I found by searching the web for "java maximum array length" or something similar. – Dave Newton Sep 13 '21 at 19:41
  • I have been perusing the language spec and I could not find anything that specifically indicated the maximum size (although there is sufficient information about other array aspects to conclude it must be an int >= 0). – WJS Sep 13 '21 at 20:37

1 Answers1

3

According to the Java language specification.

10.4 Array Access

Arrays must be indexed by int values; short, byte, or char values may also be used as index values because they are subjected to unary numeric promotion (§5.6) and become int values.

An attempt to access an array component with a long index value results in a compile-time error.

And from my own perspective, since the Array.length returns an int, there would be no need to have an index beyond Integer.MAX_VALUE. So indexing via a long wouldn't be necessary.

WJS
  • 36,363
  • 4
  • 24
  • 39