What does it mean for a collection to be final in

2020-06-09 11:14发布

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?

4条回答
够拽才男人
2楼-- · 2020-06-09 11:24

Making the variable final makes sure you cannot re-assign that object reference after it is assigned. If you combine the final keyword with the use of Collections.unmodifiableList, you get the behaviour that you describe:

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);
    }
  }
}
查看更多
我命由我不由天
3楼-- · 2020-06-09 11:28

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楼-- · 2020-06-09 11:29

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
查看更多
Anthone
5楼-- · 2020-06-09 11:32

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.

查看更多
登录 后发表回答