Map中有一个方法为:
entrySet(): set<Map.Entry<k,v>> 作用是返回图中条目的规则集,而该集合中的每个对象都是图中一个特定的键/值对。
一开始会很好奇集合中的每个对象如何存储一键值对。通过运行以下代码便可知道其中奥妙:
import java.util.*;
public class TestExercise22_8 {
public static void main(String[] args) {
// Text in a string
String text = "Have a good day. Have a good class. " +
"Have a good visit. Have fun!";
// Create a hash map to hold words and key and count as value
HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
StringTokenizer st = new StringTokenizer(text, " .!?");
while (st.hasMoreTokens()) {
String key = st.nextToken();
if (hashMap.get(key) != null) {
int value = ((Integer)hashMap.get(key)).intValue();
value++;
hashMap.put(key, new Integer(value));
}
else {
hashMap.put(key, new Integer(1));
}
}
// Create a tree map from the hash map
TreeMap<String, Integer> treeMap =
new TreeMap<String, Integer>(hashMap);
// Get an entry set for the tree map
Set entrySet = treeMap.entrySet();
// Get an iterator for the entry set
Iterator iterator = entrySet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
原来所谓每个键值对是字符串类的形式存储,而且其结构为key + “=” + value!!!!