开课吧Java课堂:是什么TreeMap类

115 阅读2分钟

TreeMap类通过使用树实现Map接口。TreeMap提供了按排序顺序存储关键字/值对的有效手段,同时允许快速检索。应该注意的是,不像散列映射,树映射保证它的元素按照关键字升序排序。

下面的TreeMap构造函数定义为:

TreeMap( ) 
TreeMap(Comparator comp) 
TreeMap(Map m) 
TreeMap(SortedMap sm) 

第一种形式构造一个空树的映射,该映射使用其关键字的自然顺序来排序。 第二种形式构造一个空的基于树的映射,该映射通过使用Comparator comp来排序(比较函数Comparators将在本章后面进行讨论)。 第三种形式用从m的输入初始化树映射,该映使用关键字的自然顺序来排序。 第四种形式用从sm的输入来初始化一个树映射,该映射将按与sm相同的顺序来排序。

TreeMap实现SortedMap并且扩展AbstractMap。而它本身并没有另外定义其他方法。 下面的程序重新使前面的例子运转,以便在其中使用TreeMap:

import java.util.*; 
class TreeMapDemo { 
 public static void main(String args[]) { 
 // Create a tree map 
 TreeMap tm = new TreeMap(); 
 
 // Put elements to the map 
 tm.put("John Doe", new Double(3434.34)); 
 tm.put("Tom Smith", new Double(123.22)); 
 tm.put("Jane Baker", new Double(1378.00)); 
 tm.put("Todd Hall", new Double(99.22)); 
 tm.put("Ralph Smith", new Double(-19.08)); 
 // Get a set of the entries 
 Set set = tm.entrySet(); 
 // Get an iterator 
 Iterator i = set.iterator(); 
 // Display elements 
 while(i.hasNext()) { 
 Map.Entry me = (Map.Entry)i.next(); 
 System.out.print(me.getKey() + ": "); 
 System.out.println(me.getValue()); 
 } 
 System.out.println(); 
 // Deposit 1000 into John Doe's account 
 double balance = ((Double)tm.get("John Doe")).doubleValue(); 
 tm.put("John Doe", new Double(balance + 1000)); 
 System.out.println("John Doe's new balance: " + 
 tm.get("John Doe")); 
 } 
} 

下面是该程序的输出结果:

Jane Baker: 1378.0 
John Doe: 3434.34 
Ralph Smith: -19.08 
Todd Hall: 99.22 
Tom Smith: 123.22 
John Doe’s current balance: 4434.34 

注意对关键字进行了排序。然而,在这种情况下,它们用名字而不是用姓进行了排序。可以通过在创建映射时,指定一个比较函数来改变这种排序。在下一节将介绍如何做。