I am stuck in trying to figure out if arrays pass references to that object or the value.
I'm not quite sure I understand your implicit question correctly, but Java arrays store their elements by value. That means an int
array will store int elements while an Object
array will store references to objects, and thus if you change the array element you'll change the reference to "point" to a differnt object while changing the object that is being referenced would not cause any direct change to the array.
As for your example:
You could create an object which holds a reference to the int[][]
array (which btw is an object as well) and the offsets and size of the region you want to cover.
Then provide setters and getters which do the necessary index calculations and access the shared array, e.g. something like this:
//note that for simplicity's sake I'll omit a lot of code like constructors etc.
class Region {
int[][] sharedArray;
int xOffset;
int yOffset;
int width;
int height;
public int get(int x, int y) {
//Note: you should check the array length and offsets to prevent IndexOutOfBoundsExceptions
return sharedArray[x + xOffset][y + yOffset];
}
public set set(int x, int y, int value) {
//Note: you should check the array length and offsets to prevent IndexOutOfBoundsExceptions
sharedArray[x + xOffset][y + yOffset] = value;
}
}
int[][] array = ...;
//define a 10x10 region starting at indices x = 2 and y = 4, e.g. it spans x = [2,11] and y = [4,13]
Region r = new Region(array, 2, 4, 10, 10);
//retrieve the element at position 5/5 relative to the region
//or (5+2)/(5+4) = 7/9 in the shared array
int element = r.get( 5, 5 );