TreeMap底层数据结构是红黑树
键是唯一、有序的(升序)
常用的方法和HashMap一样。
在使用自定义对象作为key时,必须具备比较规则
常用构造方法:
(1)带外部比较器的构造方法
public TreeMap(Comparator<? super K> comparator) { this.comparator = comparator; } |
(2)无参构造
public TreeMap() { comparator = null; }
|
TreeMap的键是有序的升序排列,这是怎么做到的?
首先键值是个String类型的字符串,而String类型实现了Comparable<String>接口,这是内部比较器。使用了内部比较器的comareTo的方法.
public int compareTo(String anotherString) { int len1 = value.length; int len2 = anotherString.value.length; int lim = Math.min(len1, len2); char v1[] = value; char v2[] = anotherString.value;
int k = 0; while (k < lim) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } k++; } return len1 - len2; } |
如果我们不想根据字母的升序排序,想用其他规则进行排序呢?比如根据键值的字符长度排序
这时我们可以用外部比较器去实现。
创建TreeMap对象,使用前面的第一个构造方法创建对象。
自己写一个类继承Comparator,编写自己的规则。
问号处填comLength
这样TreeMap的键值就可以根据你写的外部比较器进行排序了。
TreeMap怎么知道用外部比较器还是内部比较器呢?
// split comparator and comparable paths Comparator<? 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; else return t.setValue(value); } while (t != null); } else { //内部 if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") 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; else return t.setValue(value); } while (t != null); } |