Java 我的数组列表的 contains() 没有在循环中工作

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

我有一个数组列表,我想检查数组列表是否有某个字符串。我发现 .contains() 可以解决问题。但是当我 运行 它在循环中检查数组列表中的单词 "bot" 时。结果还包括 "chatbot" 和 "robot" 作为 "bot",这不是我想要的结果。但是,如果我在没有循环的情况下这样做,它工作得很好,我不明白为什么。

代码:

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

结果:

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

您基本上是在检查 arraylist arr2 是否包含单词 'bot' 而它不包含。您必须检查第一个元素是否包含该词。 arr2[0].包含("bot")

如果您只想匹配确切的字符串,请使用 .equals 而不是 .contains:

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