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

前端 未结 10 1974
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:18

    Yes, you should return a a copy of the array:

     public String[] getArr()
     {
        return Arrays.copyOf(arr);
     }
    

提交回复
热议问题