# Replace indexOf() with contains()
# Description
This rule replaces calls to indexOf() on instances of String
s or Collection
s with calls to the contains()
method.
contains()
was introduced in Java 1.4 and helps to make the code more readable.
# Benefits
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, the contains method is better suited to express this intent.
Clearer intent means better readability.
# Tags
# Code Changes
# Replacing indexOf()
by !contains()
on String
Pre
String hello = "Hello World";
if (hello.indexOf("ello") == -1) {
println(hello);
}
Post
String hello = "Hello World";
if (!hello.contains("ello")) {
println(hello);
}
# Replacing indexOf()
by contains()
on String
Pre
String hello = "Hello World";
if (hello.indexOf("ello") >= 0) {
println(hello);
}
Post
String hello = "Hello World";
if (hello.contains("ello")) {
println(hello);
}
# Replacing indexOf()
by !contains()
on Collection
Pre
if (0 > list.indexOf(string)) {
list.add(string);
}
Post
if (!list.contains(string)) {
list.add(string);
}
# Replacing indexOf()
by contains()
on Collection
Pre
if (list.indexOf(string) >= 0) {
list.add(string);
}
Post
if (list.contains(string)) {
list.add(string);
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.
# Properties
Property | Value |
---|---|
Rule ID | IndexOfToContains |
First seen in jSparrow version | 2.2.0 |
Minimum Java version | 5 |
Remediation cost | 2 min |