File: CollectionUndefinedEquality.md

package info (click to toggle)
error-prone-java 2.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 15,076 kB
  • sloc: java: 171,398; xml: 1,459; sh: 34; makefile: 7
file content (28 lines) | stat: -rw-r--r-- 1,007 bytes parent folder | download
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
26
27
28
Using `Collection`s (and other types which rely on equality) to contain elements
with undefined equality is error-prone. For example, `Collection` itself does
not have well-defined equality: the `List` and `Set` subinterfaces are not
necessarily comparable.

```java
ImmutableList<Collection<Integer>> collectionsOfIntegers =
    ImmutableList.of(ImmutableSet.of(1, 2), ImmutableSet.of(3, 4));

collectionsOfIntegers.contains(ImmutableSet.of(1, 2)); // true
collectionsOfIntegers.contains(ImmutableList.of(1, 2)); // false
```

```java
boolean containsTest(Collection<CharSequence>> charSequences) {
  // True if `charSequences` actually contains Strings, but otherwise not necessarily.
  return charSequences.contains("test");
}
```

In this case, an appropriate fix may be,

```java
boolean containsTest(Collection<CharSequence>> charSequences) {
  // True if `charSequences` actually contains Strings, but otherwise not necessarily.
  return charSequences.stream().anyMatch("test"::contentEquals);
}
```