How do I prevent the modification of a private field in a class?

前端 未结 10 1759
Happy的楠姐
Happy的楠姐 2020-12-22 16:45

Imagine that I have this class:

public class Test
{
  private String[] arr = new String[]{\"1\",\"2\"};    

  public String[] getArr() 
  {
    return arr;
         


        
10条回答
  •  时光说笑
    2020-12-22 17:37

    You must return a copy of your array.

    public String[] getArr() {
      return arr == null ? null : Arrays.copyOf(arr, arr.length);
    }
    

提交回复
热议问题