为什么Set中的元素必须实现Comparable接口?

来源:百度知道 编辑:UC知道 时间:2024/06/29 21:03:04
再往Set中添加(add)元素时,要用到comparato方法吗?
补充一下 说错了,为什么TreeSet元素必须实现Comparable接口?添加(add)元素时,要用到comparato方法吗?

所有的Set最好都要实现,实现它的目的就是为了在all某个元素的时候判断Set中不存在这个元素,实现Comparable接口就等于实现了这个过程,否则你的Set就跟Collection一样了。。没必要实现为Set了

谁说的!

SortedSet需要实现那个接口,不是所有的set都要实现

因为元素是有顺序的,所以要有对象排序的方法,用来比较两个对象的大小

sort
public static <T extends Comparable<? super T>> void sort(List<T> list)Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

The specified list must be modifiable, but need not be resizable.

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high s