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

杀马特。学长 韩版系。学妹 提交于 2019-12-03 11:16:11

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

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.

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.

kirti

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