Without seeing your code, it's hard to say what exactly is happening in your program. Maybe something like the following is happening.
Maybe you have a class that has a method that returns a mutable, private member. When you do this, and some other class calls this method, it will be able to change the content of the object that the private member variable refers to. Here is an example:
import java.util.Arrays;
class Example {
// Private member variable
private int[] data = { 1, 2, 3 };
// Method that returns the private member variable
public int[] getData() {
return data;
}
public void showData() {
System.out.println(Arrays.toString(data));
}
}
public class Main {
public static void main(String[] args) {
Example example = new Example();
// Prints: [1, 2, 3]
example.showData();
// Get the array
int[] x = example.getData();
// We can modify the array here!
x[0] = 4;
// Prints: [4, 2, 3]
example.showData();
}
}
This is because objects are arrays, and variables such as data
and x
are references to the same array object - there's only one array and data
and x
both refer to that one array. If you modify the array, you'll see the changes through both variables.
If you want to avoid this, then you shouldn't expose the array by returning it directly in the getData()
method in class Example
. You should make a copy of the array:
public int[] getData() {
// Return a copy of the array
return Arrays.copyOf(data, data.length);
}