Java tip: Immutable collections

/ 2015-02-06 12:24

If a method returns a collection, you often don’t want the caller to be able to mess around with the resulting collection. In the following code the caller is able to do that:

private List<Thing> things;

public List<Thing> getThings() {
    return things;
}

To prevent this, you can make a copy of the list manually, but that is boring to implement and slow. What you’d actually want is a wrapper for the list, that passes calls like get() and size() to the original list object, and that blocks calls like set() and add(). Guess what: such a wrapper exists, as I discovered today. It is called Collections.unmodifiableList().

So you can just do the following:

private List<Thing> things;

public List<Thing> getThings() {
    return Collections.unmodifiableList(things);
}

There are some more methods like this, such as unmodifiableMap() and unmodifiableSet().