Java 哈希集 returns false 而不是 true

Java Hashset returns false instead of true

这段代码一直返回false,我不明白为什么。

List<String> angry = new ArrayList<String>();
while ((anger = angerSt.readLine()) != null) {
    angry.add(anger);
}
angerSt.close();
String[] angrywords = angry.toArray(new String[0]);
String word = "mad"
Set<String> angryWordSet = new HashSet<String>(Arrays.asList(angrywords));
if(angryWordSet.contains(word)) 
{
    System.out.print("Yes");
    return true;
}
else return false;

angryWordSet 包含字符串 mad、angry、livid 和 fuming。我把它打印出来以确保它在那里。我不知何故不断变得错误。有人可以帮忙吗?

我认为,您必须检查每个 angryWordSet 元素是否存在前导和尾随空格。

for (String s : angryWordSet) {
    if (s.trim().equals(word)) return true;
}
return false;

关于尝试给出答案的错误。我会留下之前答案的一部分,希望它对某人有所帮助。

Object[] toArray() returns an array containing all of the elements in this list in proper sequence (from first to last element). The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array.

<T> T[] toArray(T[] a) returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

以下代码完美运行:

public static void main(String s[])
{
    List<String> angry = new ArrayList<String>();
    angry.add("a");
    angry.add("b");
    angry.add("c");
    angry.add("mad");
    angry.add("b");
    angry.add("b");
    String word = "mad";
    Set<String> angryWordSet = new HashSet<String>(angry);
    if (angryWordSet.contains(word))
    {
        System.out.print("Yes");

    }
    else
    {
        System.out.print("No");
    }
}

我假设当您执行 readline 时,单词中添加了 '\n' 或 '\r' 字符,这就是它与 "word" 变量不匹配的原因。请验证,我没有测试它:)