How to get byte [] from the specific position of another byte [] without a copy?

In java, I am wondering how can I get byte[] another byte[] from a specific position without copying it?

Example:

 byte[] bytes1 = new byte[100]; for (int i = 0; i < 100; i++) { bytes1[i] = (byte)(i+1); } byte[] byte2; 

How can I point byte2 to byte1 at position 10? I want byte2 have: [0] = 10, [1] = 11, [2] = 12

Is it possible?

I tried with ByteBuffer, but without any success.

+5
source share
3 answers

The only thing that is not related to internal VMs (yes, you can perform pointer arithmetic using JNI calls and so on) uses a method similar to Arrays.asList(bytes1).subList(startIndex, endIndex) (note that asList() not working with primitive arrays by itself, you will have to write or find on the network a similar implementation for primitives; http://fastutil.di.unimi.it/docs/it/unimi/dsi/fastutil/bytes/ByteList.html#subList% 28int comes to mind here) - note that you get the List view this way, not byte[] , since that would be practically impossible in Java (except for x ak VM, remember me).

Alternatively, do what you said - use java.nio.Buffer , ByteBuffer specifically, since it is a Java pointer to a memory pointer; with ByteBuffer array ByteBuffer you can essentially either directly access the array or access buffers in an abstract / modified (for example, offset) way.

 ByteBuffer bytes1 = ByteBuffer.allocate(100); for (int i = 0; i < 100; i++) { bytes1.put((byte)(i+1)); } bytes1.position(offset); ByteBuffer byte2 = bytes1.slice(); 

or even

 byte[] bytes1 = new byte[100]; for (int i = 0; i < 100; i++) { bytes1[i] = (byte)(i+1); } ByteBuffer bytes1 = ByteBuffer.wrap(bytes1); bytes1.position(offset); ByteBuffer byte2 = bytes1.slice(); 
+4
source

Sorry, you canโ€™t. What you are asking for is essentially C / C ++ pointer arithmetic, and there is no such thing in Java.

However, if you want to use a different interface, you might be in luck with the Commons Primitives ArrayByteList . This is not a simple List<Byte> because it is supported by a true byte array - therefore, the memory overhead due to the use of byte objects. You will still have some overhead object, but this is acceptable in practical cases.

Most importantly, it supports slices using the ArrayByteList.subList() method, which does not create a copy. You can check the source code , the slice is implemented as a reference to the source array plus two markers for the start and end positions.

However, keep in mind that avoiding copying means that changes to the slice are reflected in the original array. This is probably what you want, but be very careful anyway - especially if you are not coming from a C / C ++ background where these things are common practice.

+3
source

Sorry, you canโ€™t.

In java, every array is an object. Besides storing items, it also saves the length of the array.

0
source

Source: https://habr.com/ru/post/1209152/


All Articles