我们可以在Java中用Byte数组存储的最大元素数量是多少?

时间:2022-06-20 21:28:39

I'm working on a watermarking so I am converting PNG image to byte array and then hard-code the values of that byte array in my code.

我正在进行水印,所以我将PNG图像转换为字节数组,然后在我的代码中硬编码该字节数组的值。

But when I'm doing this with the image of 100x100 its gives an error that code is too large and as far as I know this error is due to the supported size of an byte array elements which is actually 64kb only.

但是当我用100x100的图像执行此操作时,它会产生一个代码太大的错误,据我所知,这个错误是由于字节数组元素支持的大小,实际上只有64kb。

Please and tell me if there is any better way of doing this thing?

请告诉我是否有更好的方法来做这件事?

1 个解决方案

#1


2  

The maximum number of elements in an array is Integer.MAX_VALUE or about 2 billion regardless of the type of the array.

无论数组的类型如何,数组中的最大元素数为Integer.MAX_VALUE或大约20亿。

When you initialise an array in Java, it does so in code, one element at a time. The assumption is you won't be initialising large arrays in Java. The limit for any method including the static initialisation block for initialising a Class or a constructor is 64K, and it is this limit which you appear to be hitting.

在Java中初始化数组时,它在代码中执行,一次一个元素。假设您不会在Java中初始化大型数组。包括用于初始化Class或构造函数的静态初始化块的任何方法的限制是64K,并且这是您看起来正在击中的限制。

There is two ways around this;

有两种方法可以解决这个问题;

  • read the data from a file. Then you can have arrays up to 2 GB - 1.
  • 从文件中读取数据。然后,您可以拥有最大2 GB - 1的阵列。
  • store the data in a String which is not initialised this way. You can convert the data to a byte[] using s.getBytes(StandardCharsets.ISO_8859_1)
  • 将数据存储在未以这种方式初始化的String中。您可以使用s.getBytes(StandardCharsets.ISO_8859_1)将数据转换为byte []

Most likely the best option is to store the data in a file.

最有可能的最佳选择是将数据存储在文件中。

#1


2  

The maximum number of elements in an array is Integer.MAX_VALUE or about 2 billion regardless of the type of the array.

无论数组的类型如何,数组中的最大元素数为Integer.MAX_VALUE或大约20亿。

When you initialise an array in Java, it does so in code, one element at a time. The assumption is you won't be initialising large arrays in Java. The limit for any method including the static initialisation block for initialising a Class or a constructor is 64K, and it is this limit which you appear to be hitting.

在Java中初始化数组时,它在代码中执行,一次一个元素。假设您不会在Java中初始化大型数组。包括用于初始化Class或构造函数的静态初始化块的任何方法的限制是64K,并且这是您看起来正在击中的限制。

There is two ways around this;

有两种方法可以解决这个问题;

  • read the data from a file. Then you can have arrays up to 2 GB - 1.
  • 从文件中读取数据。然后,您可以拥有最大2 GB - 1的阵列。
  • store the data in a String which is not initialised this way. You can convert the data to a byte[] using s.getBytes(StandardCharsets.ISO_8859_1)
  • 将数据存储在未以这种方式初始化的String中。您可以使用s.getBytes(StandardCharsets.ISO_8859_1)将数据转换为byte []

Most likely the best option is to store the data in a file.

最有可能的最佳选择是将数据存储在文件中。