Java的集合set中HashSet、LinkedHashSet、TreeSet用法比较

HashSet:

  • 底层实现是通过HashMap存储元素,HashSet的元素是存储在HashMap的Key中,而value统一使用一个object对象
  • 使用key保证了唯一性,但不保证顺序
  • 线程不安全,存储速度快
 Set<String> hashSet = new HashSet<>();
 hashSet.add("one");
 hashSet.add("two");
 hashSet.add("three");
 hashSet.add("four");
 System.out.println(hashSet);
 //结果
 [two, one, three, four]

LinkedHashSet:

  • 与HashSet相比,保证了数据插入的顺序
 Set<String> linkedSet = new LinkedHashSet<>();
 linkedSet.add("one");
 linkedSet.add("two");
 linkedSet.add("three");
 linkedSet.add("four");
 System.out.println(linkedSet);
 //结果
 [one, two, three, four]

TreeSet

  • 与HashSet相比,TreeSet是可以确保元素 处于排序状态,默认是按照元素对的自然排序(升序排列)
  • 底层实现是红黑树的数据结构
  • 如果一个对象需要使用TreeSet来存储,则该对象必须实现Comparable接口
Set<String> treeSet = new TreeSet<>();
treeSet.add("one");
treeSet.add("two");
treeSet.add("three");
treeSet.add("four");
System.out.println(treeSet);
//结果
[four, one, three, two]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值