Java Final arraylist

前端 未结 4 1414
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 08:44

My question is regarding declaring an arraylist as final. I know that once I write final ArrayList list = new ArrayList(); I can add, delete objects from this list,

4条回答
  •  Happy的楠姐
    2021-02-05 09:46

    When you say

    final ArrayList list = new ArrayList();
    

    this means that the variable list will always point to the same ArrayList object. There are two situations in which this can be useful.

    1. You want to make sure that no-one reassigns your list variable once it has received its value. This can reduce complexity and helps in understanding the semantics of your class/method. In this case you are usually better off by using good naming conventions and reducing method length (the class/method is already too complex to be easily understood).
    2. When using inner classes you need to declare variables as final in an enclosing scope so that you can access them in the inner class. This way, Java can copy your final variable into the inner class object (it will never change its value) and the inner class object does not need to worry what happens to the outer class object while the inner class object is alive and needs to access the value of that variable.

    The second part of your question is about the difference between

    ArrayList list = new ArrayList();
    

    and

    private static final ArrayList list = new ArrayList();
    

    The difference of course are the modifiers. private means not visible outside the class, static means that it is defined on the class level and doesn't need an instance to exist, and final is discussed above. No modifiers means package-private or default access.

提交回复
热议问题