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

前端 未结 10 1943
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

    The Collections.unmodifiableList has already been mentioned - the Arrays.asList() strangely not! My solution would also be to use the list from the outside and wrap the array as follows:

    String[] arr = new String[]{"1", "2"}; 
    public List getList() {
        return Collections.unmodifiableList(Arrays.asList(arr));
    }
    

    The problem with copying the array is: if you're doing it every time you access the code and the array is big, you'll create a lot of work for the garbage collector for sure. So the copy is a simple but really bad approach - I'd say "cheap", but memory-expensive! Especially when you're having more than just 2 elements.

    If you look at the source code of Arrays.asList and Collections.unmodifiableList there is actually not much created. The first just wraps the array without copying it, the second just wraps the list, making changes to it unavailable.

提交回复
热议问题