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

前端 未结 10 1976
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条回答
  •  猫巷女王i
    2020-12-22 17:25

    If you can use a List instead of an array, Collections provides an unmodifiable list:

    public List getList() {
        return Collections.unmodifiableList(list);
    }
    

提交回复
热议问题