Answer the question
In order to leave comments, you need to log in
How to prevent array data from being modified through a getter?
Hello. Help, please, to solve a problem. Given the code in which the array is changed through the getter. What are the ways to prevent such a change through a getter?
class two {
private final List<Integer> array = new ArrayList();
public final List<Integer> getArray() {
return array;
}
@Override
public String toString() {
return "two{" +
"array=" + array +
'}';
}
}
public class one {
public static void main(String[] args) {
two tw = new two();
System.out.println(tw);
tw.getArray().add(1);
tw.getArray().add(2);
tw.getArray().add(3);
System.out.println(tw);
}
}
Answer the question
In order to leave comments, you need to log in
It seems to me that in your case you need to look towards the Singleton pattern. For the return of the created copy, in my opinion, is still a crutch.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question