Java Final arraylist

前端 未结 4 1360
隐瞒了意图╮
隐瞒了意图╮ 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条回答
  •  -上瘾入骨i
    2021-02-05 09:24

    You say "I can add, delete (and find) objects", but who is I?

    The different between your two cases concerns from which code those list operations can be called.

    In general you need to consider the scope of the declaration, you greatly increase the maintainability of code if you reduce the visibility of your variables. If you have a class:

    Public Class MyThing {
       public int importantValue;
    
       // more code
    }
    

    That important value can be changed by any other code, anywhere else in an application. If instead you make it private and provide a read accessor:

    Public Class MyThing {
       private int importantValue;
    
       public int getImportantValue(){
           return importantValue;
       }
    
       // more code
    }
    

    you now know only the class itself can change the value - for large applications this massively increases maintainability. So declaring the list private limits what code can see, and change the contents of the list.

    The use of static makes the list shared by all instances of the class, rather than each instance getting its ovn copy.

提交回复
热议问题