Use Arrays.asList Instead of Manual Loop Copy

ID

java.use_arrays_aslist

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Best practice

Language

Java

Tags

best-practice, efficiency

Description

Reports classic counter-based for-loops that manually copy array elements into a list one by one, when Arrays.asList(), List.of(), or Collections.addAll() would be clearer and less error-prone.

Rationale

Manually iterating an array to build a list is verbose, introduces potential off-by-one errors, and obscures the intent. The JDK provides built-in methods that express the same operation in a single call:

// Bad - manual loop copy
String[] arr = getNames();
List<String> list = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
    list.add(arr[i]);
}

Remediation

Replace the loop with one of the JDK utility methods:

// Good - Arrays.asList (returns fixed-size list backed by the array)
List<String> list = Arrays.asList(arr);

// Good - List.of (returns unmodifiable list, Java 9+)
List<String> list = List.of(arr);

// Good - Collections.addAll (adds to an existing collection)
List<String> list = new ArrayList<>();
Collections.addAll(list, arr);