# 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

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