19.JAVA编程思想——使用Maps
Map(接口) 维持“键-值”对应关系(对),以便通过一个键查找相应的值HashMap* 基于一个散列表实现(用它代替Hashtable)。针对“键-值”对的插入和检索,这种形式具有最稳定的性能。可通过构建器对这一性能进行调整,以便设置散列表的“能力”和“装载因子”。ArrayMap 由一个ArrayList 后推得到的Map。对反复的顺序提供了精确的控制。面向非常小的Map 设计,特别是那些需要经常创建和删除的。对于非常小的Map,创建和反复所付出的代价要比HashMap 低得多。但在Map 变大以后,性能也会相应地大幅度降低。TreeMap 在一个“红-黑”树的基础上实现。查看键或者“键-值”对时,它们会按固定的顺序排列(取决于Comparable 或Comparator)。TreeMap 最大的好处就是我们得到的是已排好序的结果。
TreeMap 是含有subMap()方法的唯一一种Map,利用它可以返回树的一部分。
1 代码1
import java.util.*;
public class Map1 {
public finalstaticString[][] 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 finalstaticString[][] testData2 = { { "Belligerent", "Disruptive influence" },
{ "Lazy", "Motivational problems" }, { "Comatose", "Excellent behavior" } };
public staticMap fill(Map m, Object[][] o){
for (int i = 0; i < o.length; i++)
m.put(o[i][0], o[i][1]);
return m;
}
// Producing aSet of the keys:
public staticvoidprintKeys(Map m) {
System.out.print("Size = " + m.size() + ", ");
System.out.print("Keys: ");
Collection1.print(m.keySet());
}
// Producing aCollection of the values:
public staticvoidprintValues(Map m) {
System.out.print("Values: ");
Collection1.print(m.values());
}
// Iteratingthrough Map.Entry objects (pairs):
public staticvoidprint(Map m){
Collection entries = m.entrySet();
Iterator it = entries.iterator();
while (it.hasNext()) {
Map.Entry e = (Map.Entry) it.next();
System.out.println("Key = "+ e.getKey() + ", Value = "+ e.getValue());
}
}
public staticvoidtest(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 staticvoidmain(String args[]){
System.out.println("Testing HashMap");
test(new HashMap());
System.out.println("Testing TreeMap");
test(new TreeMap());
}
} /// :~
2 执行结果
TestingHashMap
Size= 7, Keys: Sleepy Happy Sneezy Grumpy Doc Dopey Bashful
Values:Prefers dark, quiet places Cheerful disposition Struggles with allergies Needsto work on attitude Fantasizes about advanced degree 'A' for effort Needsself-esteem workshop
Key= Sleepy, Value = Prefers dark, quiet places
Key= Happy, Value = Cheerful disposition
Key= Sneezy, Value = Struggles with allergies
Key= Grumpy, Value = Needs to work on attitude
Key= Doc, Value = Fantasizes about advanced degree
Key= Dopey, Value = 'A' for effort
Key= Bashful, Value = Needs self-esteem workshop
m.containsKey("Dopey"):true
m.get("Dopey"):'A' for effort
m.containsValue("'A'for effort"): true
Size= 10, Keys: Lazy Sleepy Comatose Happy Sneezy Grumpy Doc Dopey BelligerentBashful
Size= 9, Keys: Lazy Sleepy Comatose Happy Sneezy Grumpy Doc Dopey Bashful
m.isEmpty():true
m.isEmpty():true
TestingTreeMap
Size= 7, Keys: Bashful Doc Dopey Grumpy Happy Sleepy Sneezy
Values:Needs self-esteem workshop Fantasizes about advanced degree 'A' for effortNeeds to work on attitude Cheerful disposition Prefers dark, quiet placesStruggles with allergies
Key= Bashful, Value = Needs self-esteem workshop
Key= Doc, Value = Fantasizes about advanced degree
Key= Dopey, Value = 'A' for effort
Key= Grumpy, Value = Needs to work on attitude
Key= Happy, Value = Cheerful disposition
Key= Sleepy, Value = Prefers dark, quiet places
Key= Sneezy, Value = Struggles with allergies
m.containsKey("Dopey"):true
m.get("Dopey"):'A' for effort
m.containsValue("'A'for effort"): true
Size= 10, Keys: Bashful Belligerent Comatose Doc Dopey Grumpy Happy Lazy SleepySneezy
Size= 9, Keys: Bashful Comatose Doc Dopey Grumpy Happy Lazy Sleepy Sneezy
m.isEmpty():true
m.isEmpty():true
3 代码解释
printKeys(),printValues()以及print()方法并不只是有用的工具,它们也清楚地揭示了一个Map Collection“景象”的产生过程。keySet()方法会产生一个Set,它由Map 中的键后推得来。在这儿,它只被当作一个Collection 对待。values()也得到了类似的对待,它的作用是产生一个List,其中包含了Map中的所有值(注意键必须是独一无二的,而值可以有重复)。由于这些Collection 是由Map 后推得到的,所以一个Collection 中的任何改变都会在相应的Map 中反映出来。
print()方法的作用是收集由entries 产生的Iterator(反复器),并用它同时打印出每个“键-值”对的键和值。程序剩余的部分提供了每种Map 操作的简单示例,并对每种类型的Map 进行了测试。当创建自己的类,将其作为Map 中的一个键使用时,必须注意到和以前的Set 相同的问题。