I notice that when you create an array, it can only go up to the size of an int since that is the only thing it accepts. How do I create one that fits the size of a long?
-
See this question: http://stackoverflow.com/questions/1071858/java-creating-byte-array-whose-size-is-represented-by-a-long – wchargin May 03 '13 at 02:45
-
1Why you need such a big array? It seems there is a design problem. – Drogba May 03 '13 at 02:45
-
You could do multidimensional array of Integer.MAX_VALUE-1 for each dimension, but that would be the end of your memory. – Voicu May 03 '13 at 02:47
-
One wonders what actual need would be served by allocating memory for more than 2 billion elements. When dealing with such large datasets, the best solution often is to filter your data with queries first and then deal with the smaller and more efficient result sets. – scottb May 03 '13 at 02:51
-
@Drogba At first, I needed that big of an array, but then I figured an alternative. Now I just got to figure out how to use the math.sqrt() method with a long. Any ideas? – dalawh May 03 '13 at 02:57
-
@dalawh You can pass a `long` to `Math.sqrt`. It should work. – Drogba May 03 '13 at 03:02
-
holding that many of records in memory is just asking for trouble. should redesign using some kind of streaming pattern – Dapeng May 03 '13 at 04:17
4 Answers
You could use a two-dimensional array.
E.g.
Object[][] objects = new Object[Integer.MAX_VALUE][Integer.MAX_VALUE];

- 843
- 7
- 17
Currently, Java arrays are limited to int
indices, by the Java language specification. (See section 10.4, "Array Access".)
Allowing long
indices was proposed as part of Project Coin, prior to Java 7, but the proposal was not accepted.
An alternative is to use an object representing a vector of elements that supports a long index.

- 84,978
- 11
- 107
- 151
According to the Java Language Specification (see: http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html), you may only index into an array using a int
(or a short
, byte
, or char
, which are treated as int
for this purpose).
Bear in mind that the need to index into an array using a long assumes that you will have > ~2 gigs of available contiguous memory. Depending on your garbage collection strategy and your total allocated memory, this may be difficult to achieve.

- 5,487
- 1
- 25
- 35
You can only create a BigArray class based on several arrays and which will have set / get methods with long arguments.

- 133,369
- 30
- 199
- 275