
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
80 lines
2.0 KiB
Plaintext
80 lines
2.0 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Using a loop to copy an array or a subset of an array is simply wasted code when there are built-in functions to do it for you. Instead, use ``++Arrays.copyOf++`` to copy an entire array into another array, use ``++System.arraycopy++`` to copy only a subset of an array into another array, and use ``++Arrays.asList++`` to feed the constructor of a new list with an array.
|
|
|
|
|
|
Note that ``++Arrays.asList++`` simply puts a ``++Collections++`` wrapper around the original array, so further steps are required if a non-fixed-size ``++List++`` is desired.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,java]
|
|
----
|
|
public void makeCopies(String[] source) {
|
|
|
|
this.array = new String[source.length];
|
|
this.list = new ArrayList(source.length);
|
|
|
|
for (int i = 0; i < source.length; i++) {
|
|
this.array[i] = source[i]; // Noncompliant
|
|
}
|
|
|
|
for (String s : source) {
|
|
this.list.add(s); // Noncompliant
|
|
}
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,java]
|
|
----
|
|
public void makeCopies(String[] source) {
|
|
this.array = Arrays.copyOf(source, source.length);
|
|
Collections.addAll(this.list, source);
|
|
}
|
|
----
|
|
|
|
|
|
=== Exceptions
|
|
|
|
Rule detects only the most idiomatic patterns, it will not consider loops with non-trivial control flow. For example, array elements that are copied conditionally are ignored.
|
|
|
|
[source,java]
|
|
----
|
|
public int[] getCopy(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
|
|
}
|
|
}
|
|
return dest;
|
|
}
|
|
----
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use "Arrays.copyOf", "Arrays.asList", "Collections.addAll" or "System.arraycopy" instead.
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 23 Jul 2015, 07:14:19 Nicolas Peru wrote:
|
|
I slightly changed the title to make it clearer. Please double check.
|
|
|
|
=== on 23 Jul 2015, 09:06:29 Ann Campbell wrote:
|
|
Thanks [~nicolas.peru].
|
|
|
|
endif::env-github,rspecator-view[]
|