I am a new bird to Java and I am confused about returning an array in Java. Below are my codes:
public class Pointer{
private final int[] data;
Pointer(){
data = new int[4];
data[0] = 1;
data[1] = 2;
data[2] = 3;
data[3] = 4;
}
public int[] test(){
return data;
}
public void print(){
int length = data.length;
int j;
for(j = 0; j < length; j++){
System.out.println(data[j]);
}
}
static public void main(String[] argv){
Pointer i = new Pointer();
int[] re = i.test();
i.print();
re[2] = 1;
i.print();
}
}
I though I returned an array of int, instead of the pointer to that, so the data should not be changed when I wrote re[2] = 1. How to make this Pointer Object immutable?