Search code examples
listimmutabilityguavafinal

CodeQuality / Guava: clear and fill a final list or assign a new Immutablelist


I have a class holding entries in a list, which can be cleared and refilled by a method from time to time. Is it considered better practise to use a normal List as final member of the class or should I create a Immutablelist each time it's refilled, therefore losing the 'final' modifier?

The reason I'm asking is because other objects can access the List from the outside, but should not be able to change them. I want to return an ImmutableList to them, but not copy it every time the accessor is called.


Solution

  • I'd actually not use Guava for this use case, but rather just tools in the JDK.

    What you should do is use a traditional, mutable list implementation -- probably an ArrayList -- in your class. However, your class should implement the getList() method as something like

    public List<Something> getList() {
      return Collections.unmodifiableList(internalList);
    }
    

    This would ensure that other objects cannot modify the list, but the list can be modified as you like.