Why is this an issue?
Most checks against an indexOf
value compare it with -1 because 0 is a valid index. Any checks which look for values >0 ignore the
first element, which is likely a bug. If the intent is merely to check inclusion of a value in a String
or a List
, consider
using the contains
method instead.
This rule raises an issue when an indexOf
value retrieved either from a String
or a List
is tested against
>0
.
Noncompliant code example
String color = "blue";
String name = "ishmael";
List<String> strings = new ArrayList<String> ();
strings.add(color);
strings.add(name);
if (strings.indexOf(color) > 0) { // Noncompliant
// ...
}
if (name.indexOf("ish") > 0) { // Noncompliant
// ...
}
if (name.indexOf("ae") > 0) { // Noncompliant
// ...
}
Compliant solution
String color = "blue";
String name = "ishmael";
List<String> strings = new ArrayList<String> ();
strings.add(color);
strings.add(name);
if (strings.indexOf(color) > -1) {
// ...
}
if (name.indexOf("ish") >= 0) {
// ...
}
if (name.contains("ae") {
// ...
}