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

前端 未结 10 1966
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:15

    You could return a copy of the data. The caller who chooses to change the data will only be changing the copy

    public class Test {
        private static String[] arr = new String[] { "1", "2" };
    
        public String[] getArr() {
    
            String[] b = new String[arr.length];
    
            System.arraycopy(arr, 0, b, 0, arr.length);
    
            return b;
        }
    }
    

提交回复
热议问题