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

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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