In Java, it won't allow me to use a long for something like this:
long size = 0xFFFFFFFF; //2^32-1
byte [] data = new byte[size];
And an int can only go as high as 0x7FFFFFFF (2^31-1). Is it possible to declare a byte array of this size?
In Java, it won't allow me to use a long for something like this:
long size = 0xFFFFFFFF; //2^32-1
byte [] data = new byte[size];
And an int can only go as high as 0x7FFFFFFF (2^31-1). Is it possible to declare a byte array of this size?
Answer is NO
as this is the max possible initialization:
int size = Integer.MAX_VALUE;
byte [] data = new byte[size];
Declare the size
as an int
and try again:
int size = 0x7FFFFFFF; // 0x7FFFFFFF == Integer.MAX_vALUE == 2^32-1
An array can only be declared to have a positive int
size, not a long
. And notice that the maximum int
positive value (and hence, the maximum possible size for an integer array, assuming there's enough memory available) is 0x7FFFFFFF == Integer.MAX_vALUE
.
Integer.MAX_VALUE is the limit for many java concepts. For example String/List can't be longer than that.
Back in 1995 when Java was created, 4MB total memory is the norm.
The same problem exists in most languages. But if we are to design a new language today, we'd certainly use long
.
The problem in your example is that the array create function expects an int as argument and you were passing a long.
This compiles:
long size = 0xFFFFFFFF; //2^32-1
byte [] data = new byte[(int)size];
But doesn't run. It doesn't run in this particular example of long
because the number is negative, and you simply can't create an array with negative number of elements. But still, it's possible to use a long variable to create an array, but it need to be a positive number and need to be cast to int, like the following:
long size = 0x00FFFFFF; //
byte [] data = new byte[(int)size];
Which will compile and work.
By the way, changing from size to Integer.MAX_VALUE
won't accomplish nothing if this exceeds your JVM memory limits.
I agree that you cannot have a byte[] with more than Integer.MAX_VALUE elements. However, you can have an array of arrays.
I suggest writing a class that has:
A constructor that takes a long size and builds a byte[][] big enough to contain that many elements.
Get and set methods that use a long index
A size() method that returns a long.
Of course, this is only practical with a 64 bit JVM and a big enough memory.
I felt even back in the 1990's that the choice of int rather than long for the array index and length types was short-sighted. Sun was selling many machines with tens of gigabytes of memory, and there has been a consistent tendency both for maximum array sizes to approach memory sizes, and for memory sizes to grow.
This is not possible. Array size supports only int values.
You could check the JDK source code for arrays. Only int values are supported.