hash类型数据的遍历
来源:互联网 发布:vmware for linux 下载 编辑:程序博客网 时间:2024/06/03 08:50
package com;import java.util.Enumeration;import java.util.HashMap;import java.util.Hashtable;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;/** * hash数据类型的遍历 */public class Test2 {Map<String, String> hm = new HashMap<String, String>();/** * 初始化hm对象 */public void initMap(){hm.put("1", "lily");hm.put("2", "lucy");hm.put("3", "lilei");hm.put("4", "josn");}/** * 第一种hash数据类型遍历。 * 通过hashmap对象的keySet()方法获取该hash对象key值得set集合, * 在对该key值集合进行遍历获取到对应的key值,在通过key值获取key对应的value */public void itera1(){System.out.println("第一种hash数据类型遍历");Iterator<String> iter;iter = hm.keySet().iterator();while(iter.hasNext()){String st = iter.next();System.out.print(hm.get(st)+" ");}System.out.println();}/** * 第二种hash数据类型遍历。 * 使用entrySet方法来获取map集合的Set<Entry<String,String>>对象。 * 核心思想:将map集合的形式转换为线性集合的形式,接着通过Iterator对象来获取线性集合中的每一个map元素 * @param args */public void itera2(){System.out.println("第二种hash数据类型遍历");Iterator<Entry<String, String>> iterator = hm.entrySet().iterator();//entrySet,方法一while(iterator.hasNext()){Map.Entry<String, String> entry = (Entry<String,String>)iterator.next();System.out.print("key="+entry.getKey()+"===value="+entry.getValue()+" ");}System.out.println();//entrySet,方法二for(Map.Entry<String, String> m :hm.entrySet()){System.out.print("key="+m.getKey()+"===value="+m.getValue()+" ");}System.out.println();}/** * 第三种hash数据类型遍历。 * 利用枚举类型来存储每一个map集合,和方法二相似 。 * 该遍历方法的对象由HashMap变为了Hashtable,所以要将迭代器Iterator对象换为Enumeration枚举对象 * @param args */public void itera3(){System.out.println("第三种hash数据类型遍历");Hashtable<String, String> ht = new Hashtable<String, String>();ht.put("1", "lily");ht.put("2", "lucy");ht.put("3", "lilei");ht.put("4", "josn");Enumeration<String> enu = ht.elements();while(enu.hasMoreElements()){System.out.print(enu.nextElement()+" ");}}public static void main(String[] args) {// TODO Auto-generated method stubTest2 test = new Test2();test.initMap();test.itera1();test.itera2();test.itera3();}}