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

前端 未结 10 1929
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:19

    The nub of the problem is that you are returning a pointer to a mutable object. Oops. Either you render the object immutable (the unmodifiable list solution) or you return a copy of the object.

    As a general matter, finality of objects does not protect objects from being changed if they are mutable. These two problems are "kissing cousins."

提交回复
热议问题