what is the sense of final ArrayList?

前端 未结 12 533
日久生厌
日久生厌 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: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 list = new ArrayList();
    list = new ArrayList(); // 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 list = Collections.unmodifiableList(new ArrayList(...));
    

提交回复
热议问题