简体   繁体   中英

Java Hashset returns false instead of true

This block of code keeps returning false, and I can't figure out why.

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;

The angryWordSet contains the strings mad, angry, livid and fuming. I printed it out to make sure it was there. I somehow keep getting false though. Can someone help with this?

Following code works perfectly:

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

I am assuming when you do readline, words have '\\n' or '\\r' character added to it, thats why its not matching with the "word" varibale. Please verify, I didnt test it :)

I think, you have to check for the existence of leading and trailing whitespaces for each angryWordSet element.

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

About the wrong attempt to give an answer. I would leave a part of the previous answer in hoping that it will be helpful for someone.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM