what is the sense of final ArrayList?

前端 未结 12 494
日久生厌
日久生厌 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: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.)

提交回复
热议问题