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

前端 未结 10 1771
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:41

    at this point of view you should use system array copy:

    public String[] getArr() {
       if (arr != null) {
          String[] arrcpy = new String[arr.length];
          System.arraycopy(arr, 0, arrcpy, 0, arr.length);
          return arrcpy;
       } else
          return null;
       }
    }
    

提交回复
热议问题