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的区别
结果显示为:
[color=red]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 ,[/color]
可以得出结论:
[color=red]HashSet按Hash函数排序

LinkedHashSet按插入顺序排序

TreeSet按字母顺序排序[/color]
set不保存重复的元素(这大家都知道)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值