Replace indexOf() with contains()

Properties

Property Value
First seen in jSparrow version 2.2.0
Minimum Java version 5
Remediation cost 2 min

Description

This rule replaces calls to indexOf() on instances of Strings or Collections 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.

Requirement & Tags

Requirements

Java 5

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);
}

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: