Why is this an issue?
The JDK provides a set of built-in methods to copy the contents of an array into another array. Using a loop to perform the same operation is less
clear, more verbose and should be avoided.
Exceptions
The rule detects only the most idiomatic patterns, it will not consider loops with non-trivial control flow. For example, loops that copy array
elements conditionally are ignored.
How to fix it
You can use:
-
Arrays.copyOf
to copy an entire array into another array
-
System.arraycopy
to copy only a subset of an array into another array
-
Arrays.asList
to create a new list with the contents of the array
-
Collections.addAll
to add the elements of a collection into another collection
Note that Arrays.asList
returns a fixed-size List
, so further steps are required if a non-fixed-size List
is
needed.
Code examples
Noncompliant code example
public void copyArray(String[] source){
String[] array = new String[source.length];
for (int i = 0; i < source.length; i++) {
array[i] = source[i]; // Noncompliant
}
}
public void copyList(List<String> source) {
List<String> list = new ArrayList<>();
for (String s : source) {
list.add(s); // Noncompliant
}
}
Compliant solution
public void copyArray(String[] source){
String[] array = Arrays.copyOf(source, source.length);
}
public void copyList(List<String> source) {
List<String> list = new ArrayList<>();
Collections.addAll(list, source);
}
public void makeCopiesConditional(int[] source) {
int[] dest = new int[source.length];
for (int i = 0; i < source.length; i++) {
if (source[i] > 10) {
dest[i] = source[i]; // Compliant, since the array elements are conditionally copied to the dest array
}
}
}
Resources
Documentation