How to get a sub array of array in Java, without copying data?
I have some library of classes, working with my data, which is being read into buffer. Is it possible somehow to avoid copying arrays again and again, passing parts of data deeper and deeper into processing methods? Well, it sounds strange, but in my particular case, there's a special writer, which divides data into blocks and writes them individually into different locations, so it just performs System.arraycopy, gets what it needs and calls underlying writer, with that new sub array. And this happens many times. What is the best approach to refactor such code?
Arrays.asList(array).subList(x, y).
This method doesn't give you an array, but a List
, which is far more flexible.
Many classes in Java accept a subset of an arrays as parameter. E.g. Writer.write(char cbuf[], int off, int len). Maybe this already suffices for your usecase.
There is no real way to wrap any data without copying and receive real array in Java. You just cannot create new array over existing memory. You have basically 2 options:
- Use methods that can accept range of array. This was already recommended.
- Use wrapper that gives some kind of abstraction that is close to array and is suitable for many applications. Will be described below.
You may use java.nio.Buffer
classes hierarchy, especially java.nio.ByteBuffer
which offers buffer abstraction on whole array or sub-ranges. Often it is what people need. This also offers many interesting abilities like 'zero copy' flip and flexible byte area representation.
Here is example of wrapping using java.nio.ByteBuffer
.
This should be very close to what you need. At least for some operations.
byte [] a1 = {0, 0, 1, 0};
ByteBuffer buf = ByteBuffer.wrap(a1,1,2);
Then you can do on buf
any ByteBuffer
operation.
Just a warning, buf.array()
returns original a1
array (backend) with all elements.