Search code examples
javaarraylistcontains

Java contains() for my arraylist is not working in a loop


i have an arraylist and I want to check whether the arraylist have a certain string. I found that .contains() can do the trick. But when i run it in a loop to check the word "bot" in an arraylist. The results also include "chatbot" and "robot" as "bot" which is not suppose to be the result that I want. But if I do it without the loop, it work just fine which I dont understand why.

The code:

// Java code to demonstrate the working of 
// contains() method in ArrayList of string 

// for ArrayList functions 
import java.util.ArrayList; 

public class test { 
    public static void main(String[] args) 
    { 

        // creating an Empty String ArrayList 
        ArrayList<String> arr = new ArrayList<String>(4); 
        ArrayList<String> arr2 = new ArrayList<String>(4);

        // using add() to initialize values 
        arr.add("chatbot"); 
        arr.add("robot"); 
        arr.add("bot"); 
        arr.add("lala"); 

        // use contains() to check if the element 
        for (int i=0;i<arr.size();i++){
            boolean ans = arr.get(i).contains("bot"); 
            if (ans) {System.out.println("1: The list contains bot"); }
            else
                {System.out.println("1: The list does not contains bot");}
        }

        System.out.println();

        for (String str : arr) {
        if (str.toLowerCase().contains("bot")) {
            System.out.println("2: The list contains bot");;
        }
        else
            {System.out.println("2: The list does not contains bot");}
        }


        // use contains() to check if the element 
        System.out.println();
        arr2.add("robot");
        boolean ans = arr2.contains("bot"); 

        if (ans) 
            System.out.println("3: The list contains bot"); 
        else
            System.out.println("3: The list does not contains bot"); 
    } 
} 

The result:

1: The list contains bot
1: The list contains bot
1: The list contains bot
1: The list does not contains bot

2: The list contains bot
2: The list contains bot
2: The list contains bot
2: The list does not contains bot

3: The list does not contains bot

Solution

  • Use .equals instead of .contains if you want to match only the exact string:

    public static void main(String s[]) {
            test.add("bot");
            test.add("ibot");
            test.add("abot");
            String str = "bot";
    
            for(int i=0;i<test.size();i++) {
                if(str.equals(test.get(i))) {
                    System.out.println("True");
                }
                else {
                    System.out.println("False");
                }
            }
        }