Java Final arraylist

前端 未结 4 1433
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  忘掉有多难
    2021-02-05 09:30

    Just to "bring a little water to your Mill" you will understand the interest of final when you'll want to make your list publically availiable but unmodifiable.

    In java one can make a list unmodifiable with Collections.unmodifiableList(modifiableList).

    Now have a look to the following code :

    public class MyClass{
      public static List MY_PUBLIC_LIST;
      static{
        ArrayList tmp = new ArrayList();
        tmp.add("a");
        tmp.add("b");
        tmp.add("c");
        MY_PUBLIC_LIST = tmp;
      }
    }
    

    Well, in anyclass, anywhere in your code you can do something like this

    MyClass.MY_PUBLIC_LIST = null;
    MyClass.MY_PUBLIC_LIST = new ArrayList();
    MyClass.MY_PUBLIC_LIST.clear();
    MyClass.MY_PUBLIC_LIST.add("1");
    

    When you add the final keyword to your variable, the first two won't be allowed

    public static final List MY_PUBLIC_LIST;
    

    But you'll still be able to modify the content of the list :

    MyClass.MY_PUBLIC_LIST.clear();
    MyClass.MY_PUBLIC_LIST.add("1");
    

    By adding a Collections.unmodifiableList(modifiableList) at the end of the static block you'll prevent this too :

    MY_PUBLIC_LIST = Collections.unmodifiableList(tmp);
    

    Ok we are almost there. Just to be sure you get the whole picture lets keep the Collections.unmodifiableList(modifiableList) but let me remove the final modifier

    public class MyClass{
      public static List MY_PUBLIC_LIST;
      static{
        ArrayList tmp = new ArrayList();
        tmp.add("a");
        tmp.add("b");
        tmp.add("c");
        MY_PUBLIC_LIST = Collections.unmodifiableList(tmp);
      }
    }
    

    What can you do in that case ?

    ...

    ...

    Well you can do whatever you want like in the first case (given that you assign the new list first) :

    MyClass.MY_PUBLIC_LIST = null;
    MyClass.MY_PUBLIC_LIST = new ArrayList();
    MyClass.MY_PUBLIC_LIST.clear();
    MyClass.MY_PUBLIC_LIST.add("1");
    

提交回复
热议问题