File: UnusedCollectionModifiedInPlace.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (25 lines) | stat: -rw-r--r-- 817 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Several of the methods in `java.util.Collections`, such as `sort` and `shuffle`,
modify collections in place. If you call one of these methods on a
newly-allocated collection and don't use it later, you are doing unnecessary
work. You probably meant to keep a reference to the newly-allocated copy of your
collection and use that in the rest of your code.

For example, this code sorts a new `ArrayList` and then throws away the result,
returning the unsorted original collection:

```java
public Collection<String> sort(Collection<String> foos) {
  Collections.sort(new ArrayList<>(foos));
  return foos;
}
```

The author probably meant:

```java
public Collection<String> sort(Collection<String> foos) {
  List<String> sortedFoos = new ArrayList<>(foos);
  Collections.sort(sortedFoos);
  return sortedFoos;
}
```