Chris
Chris

Reputation: 1643

Java: Offsetting a byte[] without performing a copy operation

I was wondering if it is possible, access a byte[] with an offset without having to copy data around?
I've looked at Arrays.*, ByteArrayInputStream and System.arraycopy, but they all require to allocate a new byte[] to copy to.

What I want is an equivalent to this in C++:

char* buffer = new char[256];
char* buf_offset = buffer + 128; // <- no copy

Upvotes: 3

Views: 1988

Answers (2)

irreputable
irreputable

Reputation: 45443

You can pass ByteBuffer around instead. It can be advanced, duplicated, sliced without copying.

ByteBuffer is really ugly and counter-intuitive. However it's being used extensively in new JDK APIs, so one can probably accept that it's a basic type.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500835

No, there's no equivalent of that. You'll just need to keep track of the offset yourself. You could always create a class to encapsulate the (data, offset) pair.

Upvotes: 1

Related Questions