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

# 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.

# Tags

# 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");
    }
});

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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