# Use Collections Singleton List

# Description

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

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) (opens new window).

# Benefits

Improves the efficiency of creating short lists.

# Tags

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

# Bytecode JDK 1.8

Pre

public void original() {
    List<String> list = Arrays.asList("value");
}
 0 iconst_1
 1 anewarray #2 <java/lang/String>
 4 dup
 5 iconst_0
 6 ldc #3 <value>
 8 aastore
 9 invokestatic #4 <java/util/Arrays.asList>
12 astore_1
13 return

Post

public void transformed() {
    List<String> list = Collections.singletonList("value");
}
0 ldc #3 <value>
2 invokestatic #5 <java/util/Collections.singletonList>
5 astore_1
6 return

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 UseCollectionsSingletonList
First seen in jSparrow version 3.8.0
Minimum Java version 1.3
Remediation cost 2 min