首先要说明的是,TreeMap仍然是Map,而不是Tree。同样的,TreeSet仍然是Set,而不是Tree。也就是说TreeMap和TreeSet不能当成树来使用,只是它们的底层是使用红黑树来实现的。
TreeMap实现了java.util.SortedMap接口,是一个已经排好序的Map。
TreeMap映射根据其键的自然顺序进行排序,或者根据创建映射时提供的 Comparator 进行排序,具体取决于使用的构造方法。
有两种方式使用TreeMap。
1.元素自然排序,即放入容器中的元素实现java.lang.Comparable接口。
package org.zzj; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { TreeMap<Person, String> treeMap = new TreeMap<Person, String>(); Person p1 = new Person("张三", 21); Person p2 = new Person("李四", 15); Person p3 = new Person("孙五", 26); Person p4 = new Person("赵六", 18); treeMap.put(p1, ""); treeMap.put(p2, ""); treeMap.put(p3, ""); treeMap.put(p4, ""); System.out.println(treeMap); p3.setAge(12); System.out.println(treeMap); } } class Person implements Comparable<Person> { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(Person o) { return this.age - o.age; } @Override public String toString() { return "name:" + name + "; age:" + age + "\n"; } }输出
{name:李四; age:15 =, name:赵六; age:18 =, name:张三; age:21 =, name:孙五; age:26 =} {name:李四; age:15 =, name:赵六; age:18 =, name:张三; age:21 =, name:孙五; age:12 =}当把孙五的年龄改为最小的时候,他仍然排在了最后,这说明 元素的顺序在放入容器的时候就已经确定了。
package org.zzj; import java.util.Comparator; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { TreeMap<Person, String> treeMap = new TreeMap<Person, String>( new Comparator<Person>() { @Override public int compare(Person o1, Person o2) { return o1.getAge() - o2.getAge(); } }); Person p1 = new Person("张三", 21); Person p2 = new Person("李四", 15); Person p3 = new Person("孙五", 26); Person p4 = new Person("赵六", 18); treeMap.put(p1, ""); treeMap.put(p2, ""); treeMap.put(p3, ""); treeMap.put(p4, ""); System.out.println(treeMap); p3.setAge(12); System.out.println(treeMap); } } class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "name:" + name + "; age:" + age + "\n"; } }输出:
{name:李四; age:15 =, name:赵六; age:18 =, name:张三; age:21 =, name:孙五; age:26 =} {name:李四; age:15 =, name:赵六; age:18 =, name:张三; age:21 =, name:孙五; age:12 =}
如果既没有让元素实现java.lang.Comparable接口,也没有在TreeMap的构造器中传入排序器,则会在添加元素的抛出错误。
显然,使用排序器有利于解耦。
HashMap通常比TreeMap快一些(树和哈希表的数据结构使然),建议多使用HashMap,在需要排序的Map时候才用TreeMap。
类似于HashSet,TreeSet也是基于TreeMap实现的。