What does it mean for a collection to be final in Java? [duplicate]

喜你入骨 提交于 2020-01-01 04:23:09

问题


What does it mean for a collection to be declared final in Java? Is it that no more elements can be added to it? Is it that the elements already there cannot be changed? Is it something else?


回答1:


No. It simply means that the reference cannot be changed.

final List list = new LinkedList(); 

.... 
list.add(someObject); //okay
list.remove(someObject); //okay
list = new LinkedList(); //not okay 
list = refToSomeOtherList; //not okay



回答2:


You are getting confused between final and immutable Objects.

final --> You cannot change the reference to the collection (Object). You can modify the collection / Object the reference points to. You can still add elements to the collection

immutable --> You cannot modify the contents of the Collection / Object the reference points to. You cannot add elements to the collection.




回答3:


You can't do this,the reference is FINAL

    final ArrayList<Integer> list = new ArrayList<Integer>();
    ArrayList<Integer> list2 = new ArrayList<Integer>();
    list=list2;//ERROR
    list = new ArrayList<Integer>();//ERROR

JLS 4.12.4

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.




回答4:


Making the variable final makes sure you cannot re-assign that object reference after it is assigned. f you combine the final keyword with the use of Collections.unmodifiableList, you ge the behavi

final List fixedList = Collections.unmodifiableList(someList);

This has as result that the list pointed to by fixedList cannot be changed. it can still be change through the someList reference (so make sure it is out of scope after this asignment.)

More simple example is taking a rainbow class adding colors of rainbow in a hashset

 public static class Rainbow {
    /** The valid colors of the rainbow. */
    public static final Set VALID_COLORS;

    static {
      Set temp = new HashSet();
      temp.add(Color.red);
      temp.add(Color.orange);
      temp.add(Color.yellow);
      temp.add(Color.green);
      temp.add(Color.blue);
      temp.add(Color.decode("#4B0082")); // indigo
      temp.add(Color.decode("#8A2BE2")); // violet
      VALID_COLORS = Collections.unmodifiableSet(temp);
    }

    /**
     * Some demo method.
     */
    public static final void someMethod() {
      Set colors = RainbowBetter.VALID_COLORS;
      colors.add(Color.black); // <= exception here
      System.out.println(colors);
    }
  }
}


来源:https://stackoverflow.com/questions/26500423/what-does-it-mean-for-a-collection-to-be-final-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!