Wednesday, 14 August 2013

Pass An Array as Argument Having a Different Start Index

Pass An Array as Argument Having a Different Start Index

How can I pass arrays in Java where I can indicate a different start index
(0th index) for the array argument. In C++, you can pass arrays like this
myMethed(myArray + 3); // passing method where begin index is 4th element
...
void myMethod(int* arr) {
int val = arr[0]; // refers to the 4th element
int val2 = arr[1]; // 5th element
}
How can I do something similar in Java. I tried copying a subset of the
array using Arrays.copyOfRange but I don't want a separate copy but the
same array with a different start index.
Of course I can do this:
myMethod(int[] arr, int startIndex) {
int val = arr[startIndex];
int val2 = arr[startIndex + 1];
}
But are there other ways without declaring a separate parameter for start
index? Thanks a lot.

No comments:

Post a Comment