views:

52

answers:

3

hi, let say i have an array that is long enough to access any of its index with int, is there any way to access the index of such an array with long? and how the java handles this kind of array? e.g.

int[] a = new int[]{1,5,2,4........9,2,1}

assume in above array that 9,2,1 are at indices that are beyond the range of int (2^32). how would i access these?

thx :)

+1  A: 

You wouldn't - array indexes are always int values in Java. It doesn't allow for an array with more than Integer.MAX_VALUE elements.

The length of an array is represented by the length field, which is of type int. Therefore it is impossible to create an array with a length greater than Integer.MAX_VALUE.

The spec doesn't explicitly call this out, but you can infer it from the types involved.

Jon Skeet
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html which I was looking for too :P
wds
The spec does mention it when talking about array creation expressions: "the type of a dimension expression must not be long."
Steve M
@Jon Skeet, it is specified in the spec. But it isn't really explicit.
Colin Hebert
Are List/Set also limited? What happens if you do toArray on a List/Set that is larger than MAX_VALUE?
willcodejavaforfood
@willcodejavaforfood: Well `List.get()` takes an `int` index... I don't think any of the collections are really expected to handle more than 2 billion elements.
Jon Skeet
@Jon Skeet, @willcodejavaforfood it depends on the implementation. You "could" have a list working with longs (and with a `get(long)`). But it would be playing with fire and breaking most of the Collection contract.
Colin Hebert
Interesting, never really thought about that :)
willcodejavaforfood
Do you really have an array with over 2 billion elements? This seems slightly excessive, even with the huge amounts of memory available on modern computers. I'm wondering if this is a real application or just a hypothetical question. Like, what, you have a table with an entry for every person in the world or something?
Jay
A: 

You can't have a that long array. But this idea has been proposed for the project coin.

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.1) and become int values. An attempt to access an array component with a long index value results in a compile-time error.


Resources :

Colin Hebert
A: 

As others mentioned, the length and index values must be ints. If you really need this, there are workarounds though. For instance, you could have an array of very big int arrays. You could then do some modulo arithmetic on a long to determine which array you want and which index in that array is needed.

Michael McGowan