# Replace indexOf() with contains()

# 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.

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

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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