TreeSet
- 符合 Tree 的定義
- TreeSet是一個有序集合
將元素添加到集合的正確位置上使用 TreeSet 是一個不錯的選擇(排序)
對象的比較
對象即元素纽哥,只要實現(xiàn)了 Comparable 接口即可對對象進行比較
public interface Comparable<T> {
int compareTo(T other);
}
調用 a.compareTo(b)
- 如果 a 與 b 相等沼头, 返回 0
- 如果 a 位于 b 之前,則返回負值
- 如果 a 位于 b 之后,則返回正值
假設是兩個x學生進行比較圃伶,比較的是 id
public class Student implements Comparable<Student> {
private int id;
@Override
public int compareTo(Student other) {
//也可 return Integer.compare(id, other.id);
return id - other.id;//從小到大排序悲关,反之 return other.id - id;
}
}
但是注意 如果比較的是比較長的數(shù)字可能會導致 id - other.id 溢出
還有很多關于排序很有用的接口
public interface Comparator<T>{
/**
* 將兩個對象進行比較,
* 如果 a 位于 b 之前則返回負值撤逢;
* 如果兩個對象處于相同位置則后返回 0;
* 如果 a 位于 b 之后返回正值
*/
int compare(T a, T b);
}
/**
* 同時也要實現(xiàn) Comparable 接口
*/
public interface SortedSet<E> {
/**
* 返回最小的元素
*/
E first();
/**
* 返回最大的元素
*/
E last();
}
public interface Navigable<E> {
/**
* 返回大于 value 的最小元素
*/
E higher(E value);
/**
* 返回小于 value 的最大元素
*/
E lower(E value);
/**
* 返回大于等于 value 的最小元素
*/
E celling(E value);
/**
* 返回小于等于 value 的最大元素
*/
E floor(E value);
/**
* 刪除并返回這個集合中的最大元素, 為空返回 null
* @return
*/
E poolFirst();
/**
* 刪除并返回這個集合中的最小元素, 為空返回 null
*/
E poolLast();
/**
* 返回一個按照第幾按順序遍歷集合中元素的迭代器
*/
Iterator<E> descendingIterator();
}