java.util.map中的方法entrySet解析

来源:互联网 发布:finale 2016 mac 编辑:程序博客网 时间:2024/06/06 13:20

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!!!!

 

0 0
原创粉丝点击