0

I have a method given these arguments

int read( byte result[], int offset, int size ) {
}

From which I need to call a different method:

int read( byte result[], int length ) {
}

I know how to convert an array in C++ with an offset, but I have no idea how to do this in Java.

3
  • You can't. You have to create a copy of the sub-array. Commented Dec 7, 2016 at 16:56
  • Thanks @Andreas, would you mind posting this as the answer? Commented Dec 7, 2016 at 16:57
  • raw pointers are not supported by java. use System.arrayCopy or Arrays.copyOf or manual copy Commented Dec 7, 2016 at 16:58

1 Answer 1

1

You can't. You have to create a copy of the sub-array.

Easiest way to do that, is to use one of the Arrays.copyOfRange(xxx[] original, int from, int to) methods, where xxx is a primitive type or any object type.

If needed, you can copy updated values back to the original array using System.arraycopy().

In your case, the parameter is actually output-only, so you just create a new array, call the method with it, then copy the values to the original array, e.g.

int read( byte result[], int offset, int size ) {
    if (offset == 0)
        return read(result, size);
    byte[] buf = new byte[size];
    int bytesRead = read(buf, size);
    System.arraycopy(buf, 0, result, offset, bytesRead);
    return bytesRead;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.