简体   繁体   English

Java:为什么我的HashSet和TreeSet包含重复项?

[英]Java: Why does my HashSet and TreeSet contain duplicates?

When my text file contains this: 当我的文本文件包含以下内容时:

a b c b

My HashSet and TreeSet say there are 3 unique words. 我的HashSet和TreeSet说有3个唯一的单词。

When my text file contains this: 当我的文本文件包含以下内容时:

a b c a

My HashSet and TreeSet say there are 4 unique words. 我的HashSet和TreeSet说有4个唯一的单词。

Why? 为什么?

  public static int countUnique1A(WordStream words) {

    HashSet<String> hashSetA = new HashSet<String>();
    for (String i : words) {
      hashSetA.add(i);
    }

    return hashSetA.size();
  }

  public static int countUnique1B(WordStream words) {

    TreeSet<String> treeSetA = new TreeSet<String>();
    for (String i : words) {
      treeSetA.add(i);
    }
    return treeSetA.size();
  }

I guess it may be due to spaces between the words. 我猜可能是由于单词之间的空格。 Eg HashSet may contain 'a' and 'a '. 例如, HashSet可能包含“ a”和“ a”。 Can you try changing: 您可以尝试更改:

hashSetA.add(i);

to

hashSetA.add(i.trim());

We need to do the same for treeSetA as well. 我们也需要对treeSetA做同样的treeSetA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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