抓住Java中的数组的一个片段,而无需创建堆一个新的数组 [英] Grab a segment of an array in Java without creating a new array on heap

查看:161
本文介绍了抓住Java中的数组的一个片段,而无需创建堆一个新的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找Java中的方法,将返回数组的一个片段。一个例子是获取包含一个字节数组的第四个和第五个字节的字节数组。我不希望有创建堆内存中一个新的字节数组只是为了做到这一点。现在,我有以下的code:

  doSomethingWithTwoBytes(字节[] twoByteArray);无效的someMethod(字节[] bigArray)
{
      字节[]×= {bigArray [4],bigArray [5]};
      doSomethingWithTwoBytes(X);
}

我想知道是否有办法只是做 DoSomething的(bigArray.getSubArray(4,2)),其中4偏移和2是长度,例如


解决方案

免责声明:这个答案不符合问题的约束:


  

我不希望有创建堆内存中一个新的字节数组只是为了做到这一点。


老实说,我觉得我的答案是值得缺失。由@ unique72答案是正确的。伊马让了一下此编辑坐,然后我会删除这个答案。的)


我不知道的方式直接与无需额外的堆分配阵列做到这一点,但使用一个子列表包装其他答案有额外的拨款只包装 - 但不是阵列 - 这将是有用一个大的阵列的情况下。

这就是说,如果一个人正在寻找简洁,实用的方法<一href=\"http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html\"><$c$c>Arrays.copyOfRange()在Java 6中引入(2006年末):

 字节[] A =新的字节[] {0,1,2,3,4,5,6,7};//取得一[4]中,[5]字节[]子阵列= Arrays.copyOfRange(一,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屋!

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