Java 创建字节数组,其大小由 long 表示 [英] Java creating byte array whose size is represented by a long

查看:67
本文介绍了Java 创建字节数组,其大小由 long 表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个大小为 long 类型的字节数组.例如,把它想象成:

I'm trying to create a byte array whose size is of type long. For example, think of it as:

long x = _________;
byte[] b = new byte[x]; 

显然,您只能为字节数组的大小指定 int.

Apparently you can only specify an int for the size of a byte array.

在有人问我为什么需要这么大的字节数组之前,我会说我需要封装我没有编写的消息格式的数据,并且这些消息类型之一的长度为无符号整数(long 在 Java 中).

Before anyone asks why I would need a byte array so large, I'll say I need to encapsulate data of message formats that I am not writing, and one of these message types has a length of an unsigned int (long in Java).

有没有办法创建这个字节数组?

Is there a way to create this byte array?

我在想如果没有办法解决它,我可以创建一个字节数组输出流并继续向它提供字节,但我不知道对字节数组的大小是否有任何限制...

I am thinking if there's no way around it, I can create a byte array output stream and keep feeding it bytes, but I don't know if there's any restriction on a size of a byte array...

推荐答案

(对于 OP 来说可能有点晚了,但对其他人可能仍然有用)

不幸的是,Java 不支持超过 231−1 个元素的数组.byte[] 数组的最大消耗为 2 GiB 的空间,long[] 数组的最大消耗为 16 GiB.

Unfortunately Java does not support arrays with more than 231−1 elements. The maximum consumption is 2 GiB of space for a byte[] array, or 16 GiB of space for a long[] array.

虽然在这种情况下它可能不适用,但如果数组将是 稀疏,您可能可以避免使用像 Map 将每个使用的偏移量匹配到适当的值.此外,Trove 为存储原始值提供了比标准 Java 集合更节省内存的实现.

While it is probably not applicable in this case, if the array is going to be sparse, you might be able to get away with using an associative data structure like a Map to match each used offset to the appropriate value. In addition, Trove provides an more memory-efficient implementation for storing primitive values than standard Java collections.

如果数组不是稀疏的,并且您确实需要内存中的整个 blob,则您可能必须使用二维结构,例如使用 Map 匹配偏移模 1024 到正确的 1024 字节数组.即使对于稀疏数组,这种方法也可能具有更高的内存效率,因为相邻的填充单元格可以共享相同的 Map 条目.

If the array is not sparse and you really, really do need the whole blob in memory, you will probably have to use a two-dimensional structure, e.g. with a Map matching offsets modulo 1024 to the proper 1024-byte array. This approach might be be more memory efficient even for sparse arrays, since adjacent filled cells can share the same Map entry.

这篇关于Java 创建字节数组,其大小由 long 表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆