New 2 ^ 32 Java Byte Array

In Java, this will not allow me to use long for something like this:

long size = 0xFFFFFFFF; //2^32-1 byte [] data = new byte[size]; 

And int can only reach 0x7FFFFFFF (2 ^ 31-1). Is it possible to declare an array of bytes of this size?

+7
source share
6 answers

Answer NO , as this is the maximum possible initialization:

  int size = Integer.MAX_VALUE; byte [] data = new byte[size]; 
+6
source

Declare size as int and try again:

 int size = 0x7FFFFFFF; // 0x7FFFFFFF == Integer.MAX_vALUE == 2^32-1 

An array can only be declared with a positive int size, not with long . And note that the maximum int positive value (and therefore the maximum possible size for an integer array if there is enough memory) is 0x7FFFFFFF == Integer.MAX_vALUE .

+3
source

The problem in your example is that the create function of the array expects an int as an argument, and you passed a long one.

This compiles:

 long size = 0xFFFFFFFF; //2^32-1 byte [] data = new byte[(int)size]; 

But does not work. It does not work in this particular long example, because the number is negative, and you simply cannot create an array with a negative number of elements. Nevertheless, to create an array, you can use a long variable, but it must be a positive number and must be passed to int, for example:

 long size = 0x00FFFFFF; // byte [] data = new byte[(int)size]; 

What will compile and work.

By the way, switching from size to Integer.MAX_VALUE will not achieve anything if it exceeds the limits of your JVM memory.

+2
source

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 is large and builds a byte [] [] large enough to contain this many elements.

  • Get and set methods that use a long index

  • The size () method, which returns a long one.

Of course, this is practical only with a 64-bit JVM and a fairly large memory.

Back in 1990, I felt that the choice of int, and not long for array and length indices, was shortsighted. Sun sold many machines with dozens of gigabytes of memory, and there was a steady tendency towards both maximum array sizes and memory sizes, as well as larger memory sizes.

+2
source

It's impossible. The size of the array only supports int values .

You can check the JDK source code for arrays . Only int values ​​are supported.

+1
source

Integer.MAX_VALUE is the limit for many java concepts. For example, String / List cannot be longer.

Back in 1995, when Java was created, 4 MB of shared memory is the norm.

The same problem exists in most languages. But if we want to develop a new language today, we will definitely use long .

+1
source

All Articles