资讯专栏INFORMATION COLUMN

TreeSet和TreeMap的一点总结

ethernet / 2177人阅读

摘要:若是通过进行排序的话当前集合采用的。最后附上一个标准的使用的方法自然排序是实现接口并且重写了方法的另一个则是通过并且重写方法

首先简单介绍下TreeSet和TreeMap的两种排序:

自然排序

通过comparator排序

</>复制代码

  1. private static void compareWithCpmparator(){
  2. TreeSet treeSet =new TreeSet<>();
  3. List list =new ArrayList<>();
  4. list.add("a");
  5. list.add("d");
  6. list.add("b");
  7. treeSet.addAll(list);
  8. Iterator iterator =treeSet.iterator();
  9. while (iterator.hasNext()){
  10. System.out.println(iterator.next());
  11. }
  12. Comparator comparator1 = (Comparator) treeSet.comparator();
  13. if (comparator1 == null){
  14. System.out.println("comparator1是空");
  15. }else {
  16. System.out.println("comparator1不是空");
  17. }
  18. }
  19. public static void main(String[] args) {
  20. compareWithCpmparator();
  21. }

运行之后的结果如下:

</>复制代码

  1. a
  2. b
  3. d
  4. comparator1是空

这段代码里面获取的comparator是空的,Debug一遍,发现这个方法其实调用的是NavigableMap里面的comparator

</>复制代码

  1. public Comparator comparator() {
  2. return m.comparator();
  3. }

查看官网上对其的介绍:

</>复制代码

  1. Comparator comparator()
  2. Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
  3. Returns:
  4. the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys

在调用这个方法的时候若是自然排序,那么会返回一个null。若是通过comparator进行排序的话当前集合采用的comparator
查看官网对reeSet的无参构造器的解释:

</>复制代码

  1. /**

</>复制代码

  1. * Constructs a new, empty tree set, sorted according to the
  2. * natural ordering of its elements. All elements inserted into
  3. * the set must implement the {@link Comparable} interface.
  4. * Furthermore, all such elements must be mutually
  5. * comparable: {@code e1.compareTo(e2)} must not throw a
  6. * {@code ClassCastException} for any elements {@code e1} and
  7. * {@code e2} in the set. If the user attempts to add an element
  8. * to the set that violates this constraint (for example, the user
  9. * attempts to add a string element to a set whose elements are
  10. * integers), the {@code add} call will throw a
  11. * {@code ClassCastException}.

在使用TreeSet的时候,插入的元素需要实现Comparable这个接口,而刚刚的元素是String,查看String的代码发现:

</>复制代码

  1. public final class String implements java.io.Serializable, Comparable, CharSequence {

确实实现了,再测试一个没有实现的元素:

</>复制代码

  1. public class PojoTest {
  2. private int id;
  3. private String name;
  4. public PojoTest() {
  5. }
  6. public int getId() {
  7. return id;
  8. }
  9. public void setId(int id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public PojoTest(int id, String name) {
  19. this.id = id;
  20. this.name = name;
  21. }
  22. }
  23. private static void com(){
  24. TreeSet treeSet =new TreeSet<>();
  25. treeSet.add(new PojoTest(1,"a"));
  26. treeSet.add(new PojoTest(2,"b"));
  27. treeSet.add(new PojoTest(3,"c"));
  28. Iterator iterator =treeSet.iterator();
  29. while (iterator.hasNext()){
  30. System.out.println(iterator.next().getName());
  31. }
  32. }

运行结果如下:

</>复制代码

  1. Exception in thread "main" java.lang.ClassCastException: SetAndMap.TreeSetAndTreeMap.PojoTest cannot be cast to java.lang.Comparable
  2. at java.util.TreeMap.compare(TreeMap.java:1294)
  3. at java.util.TreeMap.put(TreeMap.java:538)
  4. at java.util.TreeSet.add(TreeSet.java:255)
  5. at SetAndMap.TreeSetAndTreeMap.TestTreeSet.com(TestTreeSet.java:77)
  6. at SetAndMap.TreeSetAndTreeMap.TestTreeSet.main(TestTreeSet.java:88)

很明显,所以放在TreeSet里面的元素要么是实现Comparable了的自然排序,要么是通过comparator来进行排序的。

最后附上一个标准的使用Comparator的方法

</>复制代码

  1. private static void construct(){
  2. Comparator comparator =new Comparator() {
  3. @Override
  4. public int compare(String o1, String o2) {
  5. if(o1.toCharArray()[0] >o2.toCharArray()[0]){
  6. return -1;
  7. }else if(o1.toCharArray()[0] == o2.toCharArray()[0]){
  8. return 0;
  9. }else{
  10. return 1;
  11. }
  12. }
  13. };
  14. TreeSet treeSet =new TreeSet<>(comparator);
  15. List list =new ArrayList<>();
  16. list.add("a");
  17. list.add("d");
  18. list.add("b");
  19. treeSet.addAll(list);
  20. Iterator iterator =treeSet.iterator();
  21. while (iterator.hasNext()){
  22. System.out.println(iterator.next());
  23. }
  24. Comparator comparator1 = (Comparator) treeSet.comparator();
  25. TreeSet treeSet1 =new TreeSet<>(comparator1);
  26. treeSet1.add("c");
  27. treeSet1.add("g");
  28. treeSet1.add("a");
  29. Iterator iterator1 =treeSet1.iterator();
  30. while (iterator1.hasNext()){
  31. System.out.println(iterator1.next());
  32. }
自然排序:

是实现Comparable接口并且重写了compareTo方法的

另一个comparator

则是通过comparator并且重写compare方法

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69506.html

相关文章

  • 3分钟搞掂Set集合

    摘要:下面总结一下集合常用的三个子类吧无序,允许为,底层是散列表红黑树,非线程同步有序,不允许为,底层是红黑树非线程同步迭代有序,允许为,底层是双向链表,非线程同步从结论而言我们就可以根据自己的实际情况来使用了。 前言 声明,本文用的是jdk1.8 前面章节回顾: Collection总览 List集合就这么简单【源码剖析】 Map集合、散列表、红黑树介绍 HashMap就是这么简单【源码...

    widuu 评论0 收藏0
  • 数据结构与算法(十四)深入理解红黑树JDK TreeMapTreeSet源码分析

    摘要:很多文章或书籍在介绍红黑树的时候直接上来就是红黑树的个基本性质插入删除操作等。这也不奇怪,算法的作者就是红黑树的作者之一。所以,理解树对掌握红黑树是至关重要的。 本文主要包括以下内容: 什么是2-3树 2-3树的插入操作 红黑树与2-3树的等价关系 《算法4》和《算法导论》上关于红黑树的差异 红黑树的5条基本性质的分析 红黑树与2-3-4树的等价关系 红黑树的插入、删除操作 JDK ...

    curlyCheng 评论0 收藏0
  • Java集合框架——Map接口

    摘要:第三阶段常见对象的学习集合框架集合在实际需求中,我们常常会遇到这样的问题,在诸多的数据中,通过其编号来寻找某一些信息,从而进行查看或者修改,例如通过学号查询学生信息。面试题和的区别是单列集合的顶层接口,有子接口和。 第三阶段 JAVA常见对象的学习 集合框架——Map集合 showImg(https://segmentfault.com/img/remote/1460000019683...

    princekin 评论0 收藏0
  • HashSet & TreeSet小结

    摘要:存储元素实际为存储的键值对为的,为固定对象遍历方式支持正向反向迭代器遍历和遍历顺序迭代器实现顺序遍历实现逆序遍历反向迭代器实现 HashSet & TreeSet小结 声明 文章均为本人技术笔记,转载请注明出处:https://segmentfault.com/u/yzwall HashSet小结 HashSet简介 HashSet是一个没有重复元素的集;HashSet可以存储null...

    CollinPeng 评论0 收藏0
  • Java编程基础19——Map集合&斗地主案例

    摘要:使用默认随机源对指定列表进行置换。将集合排序使用二分搜索法搜索指定列表,以获得指定对象根据元素的自然顺序,返回给定的最大元素。 1_Map集合概述和特点 A:Map接口概述 查看API可以知道: 将键映射到值的对象 一个映射不能包含重复的键 每个键最多只能映射到一个值 B:Map接口和Collection接口的不同 Map是双列的,Collection是单列的 Map...

    ygyooo 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<