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

前端 未结 10 1996
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:30

    You can also use ImmutableList which should be better than the standard unmodifiableList. The class is part of Guava libraries that was create by Google.

    Here is the description:

    Unlike Collections.unmodifiableList(java.util.List), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change

    Here is a simple example of how to use it:

    public class Test
    {
      private String[] arr = new String[]{"1","2"};    
    
      public ImmutableList getArr() 
      {
        return ImmutableList.copyOf(arr);
      }
    }
    

提交回复
热议问题