TreeMap和HashMap實現了同樣的接口Map,因此,用法基本么有區別,但是hashMap的效率高於TreeMap,在需要排序的Map才選用TreeMap。TreeMap是紅黑二叉樹實現的,打開源碼會看到核心代碼:
private transient Entry<K,V> root;
root用來存儲整個樹的根結點。root是Entry<k,v>類型,接下來看看Entry。
static final class Entry<K,V> implements Map.Entry<K,V> { K key; V value; Entry<K,V> left; Entry<K,V> right; Entry<K,V> parent; boolean color = BLACK; Entry(K key, V value, Entry<K,V> parent) { this.key = key; this.value = value; this.parent = parent; }
Entry是TreeMap的內部類,可以看到里面存儲的本身數據,左右結點,父節點以及節點的顏色。
public class TestTreeMap {
public staticvoid main(String[] args) {
TreeMap<Integer,Integer> treeMap = new TreeMap<>();
treeMap.put(2,3);
treeMap.put(3,4);
treeMap.put(1,5);
treeMap.put(7,9);
for (Integer key:treeMap.keySet()
) {
System.out.println(key+":"+treeMap.get(key));
}
}
}
由代碼發現treeMap,是按照key自增的方式排列。
如果想要上面的數據實現從大到小的順序排列:
當key為自定義的類型時,便需要實現Comparable接口,實現ComparaTo方法。有三個返回值,分別是負數,零,正數。
例如下面的例子對學生Student類進行score屬性進行從小到大的順序進行排序。
import java.util.TreeMap; public class TestTreeMap { public static void main(String[] args) { TreeMap<Integer, Integer> treeMap = new TreeMap<>(); treeMap.put(2, 3); treeMap.put(3, 4); treeMap.put(1, 5); treeMap.put(7, 9); for (Integer key : treeMap.keySet() ) { System.out.println(key + ":" + treeMap.get(key)); } TreeMap<Student, Integer> treeMap1 = new TreeMap<>(); treeMap1.put(new Student(1001,18,95),1001); treeMap1.put(new Student(1002,18,87),1002); treeMap1.put(new Student(1003,18,85),1003); treeMap1.put(new Student(1004,18,97),1004); for (Student key : treeMap1.keySet() ) { System.out.println(key + ":" + treeMap1.get(key)); } } } class Student implements Comparable<Student>{ private int age; private int id; private int score; public Student(int id, int age, int score) { this.age = age; this.id = id; this.score = score; } @Override public String toString() { return "Student{" + "age=" + age + ", id=" + id + ", score=" + score + '}'; } @Override public int compareTo(Student o) { if(this.score < o.score){ return -1; }else if(this.score == o.score){ return 0; }else { return 1; } } }
當然還想實現別的屬性排序,只需要在comparaTo里面實現即可。