Search code examples
javaarraylistfinal

what is the sense of final ArrayList?


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 is effect making it's final?


Solution

  • 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>(...));