Sunday, February 26, 2017

Immutable ArrayList

Just because the reference to the list is immutable doesn't mean that the list it refers to is immutable.
Even if list was made final this would be allowed
// changing the object which list refers to
example.getList().add("stuff");
but this would not allowed:
// changing list
example.list = new ArrayList<String>();   // assuming list is public

In order to make the list immutable (prevent also the first line), I suggest you use Collections.unmodifiableList:

             String data structure  | List data structure
           .-------------------------+------------------------------------.
Immutable  | String                  | Collection.unmodifiableList(...)   |
-----------+-------------------------+------------------------------------|
Mutable    | StringBuffer            | ArrayList                          |
           '-------------------------+------------------------------------'

No comments:

Post a Comment