Replace static final Collections with Collections.unmodifiable...()

Properties

Property Value
First seen in jSparrow version 2.2.0
Minimum Java version 2
Remediation cost 10 min
Links MutableCollection

Description

An unmodifiable Collection can be created with the matching Collections.unmodifiable...() method. Some examples are Collections.unmodifiableList(), Collections.unmodifiableSortedSet(), etc. A declaration of a Collection with the static and final modifiers is not sufficient because it might still be modifiable. The Collections which are created with Collections.unmodifiable...() throw an UnsupportedOperationException as soon as a modification is attempted.

Benefits

Applying this rule helps avoid common errors by making sure a static final field is always modifiable.

Requirement & Tags

Requirements

Java 1.2

Code Changes

Final Collection

Pre

private static final Collection<String> CONSTANT_COLLECTION = new ArrayList<String>() {
    {
        add("foo");
        add("bar");
    }
};

Post

private static final Collection<String> CONSTANT_COLLECTION = Collections.unmodifiableCollection(new ArrayList<String>() {
    {
        add("foo");
        add("bar");
    }
});

Final Map

Pre

private static final Map<String, String> CONSTANT_MAP = new HashMap() {
    {
        put("foo", "bar");
    }
};

Post

private static final Map<String, String> CONSTANT_MAP = Collections.unmodifiableMap(new HashMap() {
    {
        put("foo", "bar");
    }
});

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: