我试图通过一个小程序,并不能真正完全理解它。在某种意义上说,我错误地认为它确实如此,但我知道where =[]
如果任何人都能指出我正确的方向,我会很感激。树形图通过
import java.util.*;
public class Duplicates {
//Here we have a main method
public static void main(String[] args)
{
String[] words = args[0].split(" ");
Set<String> uniques = new TreeSet<String>();
Set<String> duplicates = new TreeSet<String>();
for (String s : words) {
if (!uniques.add(s)) {
duplicates.add(s);
}
}
uniques.removeAll(duplicates);
System.out.println("Unique words "+uniques);
System.out.print("Duplicate words "+duplicates);
}
我明白它做了什么(有点),但我不确定当你得到一个独特的词会发生什么。正如在循环中,它说if (!unique.add(s))
,这样只会处理重复...?那么当我们进入if语句时,它将处理duplicates.add(s)
。所以,我不明白如何将唯一身份添加到独特的集合?
你甚至读过[this](http://docs.oracle.com/javase/8/docs/api/java/util/Set.html)吗?......如果你确实知道,那么你会知道'Set's不能存储重复项。 – Astrobleme
阅读Set.add()和Set.removeAll()的javadoc,然后在纸上逐步执行代码,并带有包含重复项的字符串示例列表。附注:HashSet对于这个程序来说是更好的选择。 –
是的,这是程序中的重点......这是一个演讲中给我们的例子......我们删除所有重复的东西。我然而不能通过/如果 – user3443834