迭代集合

时间:2016-10-10 02:32:46

标签: java loops set hashset treeset

我正在编写一个会收到单词列表的程序。之后,它会将重复的单词和非重复单词存储到两个不同的列表中。我的代码如下:

public class Runner 
{
    public static void run (Set<String> words)
    {

        Set<String> uniques= new HashSet<String>();

        Set<String> dupes= new HashSet<String>();

        Iterator<String> w = words.iterator();

        while (w.hasNext())
        {
            if (!(uniques.add(w.next())))
                    {
                        dupes.add(w.next());
                    }
            else
            {
                uniques.add(w.next());
            }


        }

        System.out.println ("Uniques: "+ uniques);
        System.out.println ("Dupes: "+ dupes);



    }

}

但是,输出如下:

  

右,左,上,左,下

是:

  

独特:[左,右,上,下]

     

Dupes:[]

我想要的是:

  

独特:[右,左,上,下]

     

Dupes:[左]

我想用套装实现这个目标。我知道只是一个ArrayList会更容易,但我试图理解集合。

2 个答案:

答案 0 :(得分:3)

您遇到问题的原因是参数字是Set<String>。按定义设置的集合不包含重复项。参数词应该是List<String>。代码也犯了两次调用w.next()的错误。对next()的调用将导致迭代器前进。

public static void run(List<String> words) {
    Set<String> uniques= new HashSet<String>();
    Set<String> dupes= new HashSet<String>();
    Iterator<String> w = words.iterator();
    while(w.hasNext()) {
         String word = w.next();
         if(!uniques.add(word)) {
             dupes.add(word);
         }
    }
}

答案 1 :(得分:0)

  • 你正在做uniques.add(w.next())两次。为什么?
  • 此外,不要继续调用w.next() - 这会使迭代发生。调用一次并保留本地参考。

使用:

String next = w.next();
if(uniques.contains(next)) {
    // it's a dupe
} else {
    // it's not a dupe
}