Welcome

首页 / 软件开发 / JAVA / 使用Maps

使用Maps2007-05-28 yycnet.yeah.net yyc译Map(接口) 维持“键-值”对应关系(对),以便通过一个键查找相应的值
HashMap* 基于一个散列表实现(用它代替Hashtable)。针对“键-值”对的插入和检索,这种形式具有最稳定的性能。可通过构建器对这一性能进行调整,以便设置散列表的“能力”和“装载因子”
ArrayMap 由一个ArrayList后推得到的Map。对反复的顺序提供了精确的控制。面向非常小的Map设计,特别是那些需要经常创建和删除的。对于非常小的Map,创建和反复所付出的代价要比HashMap低得多。但在Map变大以后,性能也会相应地大幅度降低
TreeMap 在一个“红-黑”树的基础上实现。查看键或者“键-值”对时,它们会按固定的顺序排列(取决于Comparable或Comparator,稍后即会讲到)。TreeMap最大的好处就是我们得到的是已排好序的结果。TreeMap是含有subMap()方法的唯一一种Map,利用它可以返回树的一部分。

Map (interface)

Maintains key-value associations (pairs), so you can look up a value using a key.

HashMap*

Implementation based on a hash table. (Use this instead of Hashtable.) Provides constant-time performance for inserting and locating pairs. Performance can be adjusted via constructors that allow you to set the capacity and load factor of the hash table.

TreeMap

Implementation based on a red-black tree. When you view the keys or the pairs, they will be in sorted order (determined by Comparable or Comparator, discussed later). The point of a TreeMap is that you get the results in sorted order. TreeMap is the only Map with the subMap() method, which allows you to return a portion of the tree.

下例包含了两套测试数据以及一个fill()方法,利用该方法可以用任何两维数组(由Object构成)填充任何Map。这些工具也会在其他Map例子中用到。

//: Map1.java// Things you can do with Mapspackage c08.newcollections;import java.util.*;public class Map1 {public final static String[][] testData1 = {{ "Happy", "Cheerful disposition" },{ "Sleepy", "Prefers dark, quiet places" },{ "Grumpy", "Needs to work on attitude" },{ "Doc", "Fantasizes about advanced degree"},{ "Dopey", ""A" for effort" },{ "Sneezy", "Struggles with allergies" },{ "Bashful", "Needs self-esteem workshop"},};public final static String[][] testData2 = {{ "Belligerent", "Disruptive influence" },{ "Lazy", "Motivational problems" },{ "Comatose", "Excellent behavior" }};public static Map fill(Map m, Object[][] o) {for(int i = 0; i < o.length; i++)m.put(o[i][0], o[i][1]);return m;}// Producing a Set of the keys:public static void printKeys(Map m) {System.out.print("Size = " + m.size() +", ");System.out.print("Keys: ");Collection1.print(m.keySet());}// Producing a Collection of the values:public static void printValues(Map m) {System.out.print("Values: ");Collection1.print(m.values());}// Iterating through Map.Entry objects (pairs):public static void print(Map m) {Collection entries = m.entries();Iterator it = entries.iterator();while(it.hasNext()) {Map.Entry e = (Map.Entry)it.next();System.out.println("Key = " + e.getKey() +", Value = " + e.getValue());}}public static void test(Map m) {fill(m, testData1);// Map has "Set" behavior for keys:fill(m, testData1);printKeys(m);printValues(m);print(m);String key = testData1[4][0];String value = testData1[4][1];System.out.println("m.containsKey("" + key +""): " + m.containsKey(key));System.out.println("m.get("" + key + ""): "+ m.get(key));System.out.println("m.containsValue("" + value + ""): " + m.containsValue(value)); Map m2 = fill(new TreeMap(), testData2);m.putAll(m2);printKeys(m);m.remove(testData2[0][0]);printKeys(m);m.clear();System.out.println("m.isEmpty(): " + m.isEmpty());fill(m, testData1);// Operations on the Set change the Map:m.keySet().removeAll(m.keySet());System.out.println("m.isEmpty(): " + m.isEmpty());}public static void main(String args[]) {System.out.println("Testing HashMap");test(new HashMap());System.out.println("Testing TreeMap");test(new TreeMap());}} ///:~
printKeys(),printValues()以及print()方法并不只是有用的工具,它们也清楚地揭示了一个Map的Collection“景象”的产生过程。keySet()方法会产生一个Set,它由Map中的键后推得来。在这儿,它只被当作一个Collection对待。values()也得到了类似的对待,它的作用是产生一个List,其中包含了Map中的所有值(注意键必须是独一无二的,而值可以有重复)。由于这些Collection是由Map后推得到的,所以一个Collection中的任何改变都会在相应的Map中反映出来。
print()方法的作用是收集由entries产生的Iterator(反复器),并用它同时打印出每个“键-值”对的键和值。程序剩余的部分提供了每种Map操作的简单示例,并对每种类型的Map进行了测试。
当创建自己的类,将其作为Map中的一个键使用时,必须注意到和以前的Set相同的问题。