# Use Collections Singleton List

# Properties

Property Value
Rule ID UseCollectionsSingletonList
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.

# 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

Automatic Application of This Rule

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

# Tags

1
default
You & jSparrow
default

Hey there! May I help you? 😊