在 Java 中抓取数组的一部分,而无需在堆上创建新数组 [英] Grab a segment of an array in Java without creating a new array on heap
问题描述
我在 Java 中寻找一种方法,该方法将返回数组的一部分.一个例子是获取包含字节数组的第 4 个和第 5 个字节的字节数组.我不想为了做到这一点而在堆内存中创建一个新的字节数组.现在我有以下代码:
doSomethingWithTwoBytes(byte[] twoByteArray);void someMethod(byte[] bigArray){byte[] x = {bigArray[4], bigArray[5]};doSomethingWithTwoBytes(x);}
我想知道是否有办法只执行 doSomething(bigArray.getSubArray(4, 2))
,例如,其中 4 是偏移量,2 是长度.
免责声明:此回答不符合问题的约束:
<块引用>我不想为了做到这一点而在堆内存中创建一个新的字节数组.
(老实说,我觉得我的答案值得删除.@unique72 的答案是正确的.Imma 让这个编辑坐了一会儿,然后我会删除这个答案.)
<小时>我不知道有什么方法可以在没有额外堆分配的情况下直接使用数组执行此操作,但是使用子列表包装器的其他答案仅为包装器提供了额外的分配 - 而不是数组 - 这在以下情况下很有用大数组的情况.
也就是说,如果想要简洁,实用方法 Arrays.copyOfRange()
是在 Java 6(2006 年末?)中引入的:
byte [] a = new byte [] {0, 1, 2, 3, 4, 5, 6, 7};//得到 a[4], a[5]byte [] subArray = Arrays.copyOfRange(a, 4, 6);
I'm looking for a method in Java that will return a segment of an array. An example would be to get the byte array containing the 4th and 5th bytes of a byte array. I don't want to have to create a new byte array in the heap memory just to do that. Right now I have the following code:
doSomethingWithTwoBytes(byte[] twoByteArray);
void someMethod(byte[] bigArray)
{
byte[] x = {bigArray[4], bigArray[5]};
doSomethingWithTwoBytes(x);
}
I'd like to know if there was a way to just do doSomething(bigArray.getSubArray(4, 2))
where 4 is the offset and 2 is the length, for example.
Disclaimer: This answer does not conform to the constraints of the question:
I don't want to have to create a new byte array in the heap memory just to do that.
(Honestly, I feel my answer is worthy of deletion. The answer by @unique72 is correct. Imma let this edit sit for a bit and then I shall delete this answer.)
I don't know of a way to do this directly with arrays without additional heap allocation, but the other answers using a sub-list wrapper have additional allocation for the wrapper only – but not the array – which would be useful in the case of a large array.
That said, if one is looking for brevity, the utility method Arrays.copyOfRange()
was introduced in Java 6 (late 2006?):
byte [] a = new byte [] {0, 1, 2, 3, 4, 5, 6, 7};
// get a[4], a[5]
byte [] subArray = Arrays.copyOfRange(a, 4, 6);
这篇关于在 Java 中抓取数组的一部分,而无需在堆上创建新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!