Use Collections Singleton List

Properties

Property Value
First seen in jSparrow version 3.8.0
Minimum Java version 1.3
Remediation cost 2 min

Description

Replaces Arrays.asList with 0 or 1 parameters respectively with Collections.emptyList() or Collections.singletonList(..).

Note

Arrays.asList creates a fixed size list while Collections.singletonList creates an immutable list and therefore does not allow operations like set(int index, E element).

Benefits

Improves the efficiency of creating short lists.

Requirement & Tags

Requirements

Java 1.3

Code Changes

List with one element

Pre

List<String> list = Arrays.asList("value");

After

List<String> list = Collections.singletonList("value");

Empty List

Pre

List<String> list = Arrays.asList();

After

List<String> list = Collections.emptyList();

Static import to Arrays.asList

Pre

import static java.util.Arrays.asList;

class MyClass {
    List<String> emptyList = asList();
    List<String> singletonList = asList("value");
}


After

import java.util.Collections;

class MyClass {
    List<String> emptyList = Collections.emptyList();
    List<String> singletonList = Collections.singletonList("value");
}

Automatic Application of This Rule

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