HashSet LinkedHashSet TreeSet

public class Set1 {

static void fill(Set<String> s) {
s.addAll(Arrays.asList("f b d c e a g".split(" ")));
}
public static void test(Set s) {
System.out.println(s.getClass().getName().replaceAll("\\w+\\.", ""));
fill(s);
fill(s);
fill(s);
System.out.println(s);
s.addAll(s);
s.add("bne");
s.add("bne");
s.add("bne");
System.out.println(s);
System.out.println(s.contains("one"));

for (Iterator iterator = s.iterator(); iterator.hasNext();) {
String hashCode = (String) iterator.next();
System.out.print(hashCode + "->" + hashCode.hashCode() + " ,");
}

}
public static void main(String[] args) {
test(new HashSet<String>());
test(new TreeSet());
test(new LinkedHashSet());
}

}
此例子说明了三种Set的区别
结果显示为:
HashSet
[f, g, d, e, b, c, a]
[f, g, d, e, b, c, a, bne]
false
f->102 ,g->103 ,d->100 ,e->101 ,b->98 ,c->99 ,a->97 ,bne->97689 ,TreeSet
[a, b, c, d, e, f, g]
[a, b, bne, c, d, e, f, g]
false
a->97 ,b->98 ,bne->97689 ,c->99 ,d->100 ,e->101 ,f->102 ,g->103 ,LinkedHashSet
[f, b, d, c, e, a, g]
[f, b, d, c, e, a, g, bne]
false
f->102 ,b->98 ,d->100 ,c->99 ,e->101 ,a->97 ,g->103 ,bne->97689 ,

可以得出结论:
HashSet按Hash函数排序

LinkedHashSet按插入顺序排序

TreeSet按字母顺序排序

set不保存重复的元素(这大家都知道)

你可能感兴趣的:(C++,c,C#,F#)