首先,让我们来看看JDK中TreeSet类的add方法

/*** Adds the specified element to this set if it is not already present.* More formally, adds the specified element {@code e} to this set if* the set contains no element {@code e2} such that* <tt>(e==null ? e2==null : e.equals(e2))</tt>.* If this set already contains the element, the call leaves the set* unchanged and returns {@code false}.** @param e element to be added to this set* @return {@code true} if this set did not already contain the specified*         element* @throws ClassCastException if the specified object cannot be compared*         with the elements currently in this set* @throws NullPointerException if the specified element is null*         and this set uses natural ordering, or its comparator*         does not permit null elements*/public boolean add(E e) {return m.put(e, PRESENT)==null;}

注意抛出的异常~~

* @throws ClassCastException if the specified object cannot be compared with the elements currently in this set

也就是说,如果添加的元素不能和已有元素做比较就抛出ClassCastException异常~
那两个元素如果判断可比呢?
有两种办法,其中一种就是实现 Comparable接口
JDK中很多类都实现了Comparable接口,比如Integer
至于TreeSet为什么要这样设计,是因为这个类需要实现元素排序的功能
那如何实现的排序呢?
我们来看 TreeSet的构造方法

 /*** Constructs a new, empty tree set, sorted according to the* natural ordering of its elements.  All elements inserted into* the set must implement the {@link Comparable} interface.* Furthermore, all such elements must be <i>mutually* comparable</i>: {@code e1.compareTo(e2)} must not throw a* {@code ClassCastException} for any elements {@code e1} and* {@code e2} in the set.  If the user attempts to add an element* to the set that violates this constraint (for example, the user* attempts to add a string element to a set whose elements are* integers), the {@code add} call will throw a* {@code ClassCastException}.*/public TreeSet() {this(new TreeMap<E,Object>());}

 /*** Constructs a set backed by the specified navigable map.*/TreeSet(NavigableMap<E,Object> m) {this.m = m;}

你可以发现,排序功能实际上是由TreeMap实现的
TreeSet的add方法实际上就是调用的的TreeMap的put方法~~
最后~看看put方法的源码

/*** Associates the specified value with the specified key in this map.* If the map previously contained a mapping for the key, the old* value is replaced.** @param key key with which the specified value is to be associated* @param value value to be associated with the specified key** @return the previous value associated with <tt>key</tt>, or*         <tt>null</tt> if there was no mapping for <tt>key</tt>.*         (A <tt>null</tt> return can also indicate that the map*         previously associated <tt>null</tt> with <tt>key</tt>.)* @throws ClassCastException if the specified key cannot be compared*         with the keys currently in the map* @throws NullPointerException if the specified key is null*         and this map uses natural ordering, or its comparator*         does not permit null keys*/public V put(K key, V value) {Entry<K,V> t = root;if (t == null) {// TBD:// 5045147: (coll) Adding null to an empty TreeSet should// throw NullPointerException//// compare(key, key); // type checkroot = new Entry<K,V>(key, value, null);size = 1;modCount++;return null;}int cmp;Entry<K,V> parent;// split comparator and comparable pathsComparator<? super K> cpr = comparator;if (cpr != null) {do {parent = t;cmp = cpr.compare(key, t.key);if (cmp < 0)t = t.left;else if (cmp > 0)t = t.right;elsereturn t.setValue(value);} while (t != null);}else {if (key == null)throw new NullPointerException();Comparable<? super K> k = (Comparable<? super K>) key;do {parent = t;cmp = k.compareTo(t.key);if (cmp < 0)t = t.left;else if (cmp > 0)t = t.right;elsereturn t.setValue(value);} while (t != null);}Entry<K,V> e = new Entry<K,V>(key, value, parent);if (cmp < 0)parent.left = e;elseparent.right = e;fixAfterInsertion(e);size++;modCount++;return null;}

你可以发现,这个二叉树排序中有一条这样的语句来判断大小

cmp = k.compareTo(t.key);

这里k,也就是我们TreeSet.add(k) 方法传入的参数

Comparable<? super K> k = (Comparable<? super K>) key;

可见,插入TreeSet的对象必须实现Compareble接口

转载于:https://www.cnblogs.com/tinaluo/p/8362382.html

TreeSet集合为什么要实现Comparable?相关推荐

  1. TreeSet集合的使用

    TreeSet集合 目录 TreeSet集合 自然排序:Comparable接口的使用 案例分析 总结 比较器排序Comparator的使用 两种方法比较 public class TreeSet&l ...

  2. TreeSet集合排序方式一:自然排序Comparable

    TreeSet集合默认会进行排序.因此必须有排序,如果没有就会报类型转换异常. 自然排序 Person class->实现Comparable,实现compareTo()方法 package H ...

  3. TreeSet集合(自然排序和比较器排序)

    TreeSet集合 自然排序和比较器排序 ​ 当指执行插入排序.希尔排序.归并排序等算法时,比较两个对象"大小"的比较操作.我们很容易理解整型的 i>j 这样的比较方式,但当 ...

  4. HashSet集合和TreeSet集合

    -----------------------------------HashSet集合 ///HashSet集合的遍历 package ji_he;import java.util.HashSet; ...

  5. TreeSet集合中的自定义比较器

    import java.util.Comparator; import java.util.TreeSet; /*  当treeset集合中的元素不具备比较功能,或者具备的比较功能不是所需要的  例如 ...

  6. java基础—自定义一个比较器,对TreeSet 集合中的元素按指定方法来排序(java集合六)

    自定义一个比较器,对TreeSet 集合中的元素按指定方法来排序 import java.util.Comparator; import java.util.Iterator; import java ...

  7. java基础—TreeSet集合中储存自定义对象(java集合二)

    TreeSet集合中储存学生对象,按照其年龄进行排序 TreeSet对元素进行排序的方式一: 让元素自身具备比较功能,元素就需要实现Comparable接口,覆盖compareTo方法. TreeSe ...

  8. 本实例演示往TreeSet集合中存储自定义对象

    1 package JiHe.Set; 2 3 import java.util.Iterator; 4 import java.util.TreeSet; 5 6 /* 7 * 本实例演示往Tree ...

  9. 集合框架-Comparator和Comparable的区别

    Comparator也叫外部比较器,常在使用Collections工具类进行集合排序的时候使用.外部比较器Comparator可以理解为一个专用的比较器,当集合中的对象不支持自比较或者比较的功能不能满 ...

最新文章

  1. linux系统中的日志管理
  2. linux用户态驱动--VFIO(一)
  3. Django(part9)--GET请求
  4. Android之实现Room升级需要给一个表增加一个字段
  5. JMS--Queue实战
  6. NLPPython笔记——WordNet
  7. 湖南hp服务器虚拟化解决方案,HP刀片服务器虚拟化整合解决方案-20210729062411.docx-原创力文档...
  8. oracle如何收缩表空间,ORACLE收缩表空间
  9. Spring 框架教程
  10. A. Second Order Statistics(sort 水题)
  11. VS2019配置opencv4.1.2(永久配置)
  12. Linux centosVMware mysql用户管理、常用sql语句、mysql数据库备份恢复
  13. oracle隐含参数 开库,Oracle数据库隐含参数介绍
  14. 计算机考试后勤保障管理制度,计算机在高校后勤管理的应用
  15. 数据结构1800题-错题集-第七章
  16. 如何搭建一个谷歌广告系列?
  17. 工作日查询(一段日期内的工作日天数查询)
  18. tomcat服务莫名其妙停止
  19. python代码中的中文语法错误:SyntaxError: Non-ASCII character ‘\xe5‘ in file trade.py on line 7
  20. jenkins通过git拉取大项目出现拉取失败的情况Error fetching remote repo ‘origin’

热门文章

  1. jQ1.5中的事件系统(低版本的事件系统)
  2. ssh框架从页面传中文发生乱码时怎么解决,就是添加一个字符编码拦截器。用springframework自带的便可...
  3. Wireshark 检索命令
  4. 综述:全国软考首遭试卷丢失 20万考生措手不及
  5. 云终端要如何和服务器配置起来使用的
  6. PostgreSQL GPU 加速(HeteroDB pg_strom) (GPU计算, GPU-DIO-Nvme SSD, 列存, GPU内存缓存)
  7. Tensorflow Timeline介绍及简单使用
  8. 峰Redis学习(6)Redis 数据结构(sorted-set的操作)
  9. ESXi vSphere Client中copy paste如何启用
  10. 怎样把ACCESS导入SQL数据库