what is the sense of final ArrayList?

前端 未结 12 489
日久生厌
日久生厌 2020-11-29 00:16

Which advantages/disadvantages we can get by making ArrayList (or other Collection) final? I still can add to ArrayList new elements, remove elements and update it. But what

相关标签:
12条回答
  • 2020-11-29 00:33

    final has a lot of consequences under multi threading.

    1. JMM clearly defines a final field's initialization completion is guaranteed.

    What's not clearly defined is:

    1. Compilers are free to reorder them across memory barriers.
    2. Compilers can always read a cached copy.
    0 讨论(0)
  • 2020-11-29 00:36

    But what is effect making it's final?

    This means that you cannot rebind the variable to point to a different collection instance:

    final List<Integer> list = new ArrayList<Integer>();
    list = new ArrayList<Integer>(); // Since `list' is final, this won't compile
    

    As a matter of style, I declare most references that I don't intend to change as final.

    I still can add to ArrayList new elements, remove elements and update it.

    If you wish, you can prevent insertion, removal etc by using Collections.unmodifiableList():

    final List<Integer> list = Collections.unmodifiableList(new ArrayList<Integer>(...));
    
    0 讨论(0)
  • 2020-11-29 00:38

    You won't be able to modify its reference using new ArrayList for example.

    0 讨论(0)
  • 2020-11-29 00:38

    You cannot rebind it to a different collection as aix said.

    Example: In conjuction with immutable list implementation you get safe members which you can make public available.

    Example: When you rely on that reference does not change you need final. This is true in synchronization scenarios for example.

    There may be much more examples. It is good style to declare members final if you do not intend to change the reference at all.

    0 讨论(0)
  • 2020-11-29 00:40

    Making the variable final makes sure you cannot re-assign that objest reference after it is assigned. As you mention you can still use that lists methods to make changes.

    If you combine the final keyword with the use of Collections.unmodifiableList, you ge the behaviour you are probably trying to achieve, for instance:

    final List fixedList = Collections.unmodifiableList(someList);
    

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

    0 讨论(0)
  • 2020-11-29 00:41

    Essentially what you are trying to achieve here is making the list immutable I guess. However when you mark the list reference final it implies that the reference cant be pointed to any other list object other than this.

    If you want a final (immutable) ArrayList go for Collections class's utility method Collections.unmodifaibleList( list ) instead.

    0 讨论(0)
提交回复
热议问题