遍历Hashtable中的key和value的几种方法

package coreJava;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
/*
 * 处理原则:先取出key,再利用key获取value
 */
public class HashtableDemo {
	public static void main(String[] args) {
		Hashtable ht = new Hashtable();
		for(int i = 0;i<10;i++){
		ht.put("key"+i, "value"+i);
		}
		//利用循环遍历出key和value
		for(Iterator itr = ht.keySet().iterator();itr.hasNext();){
			String key = (String)itr.next();
			String value = (String)ht.get(key);
			System.out.println(key+" (for) "+value);
		}
		//利用循环遍历出key和value
		Iterator itr = ht.keySet().iterator();
		while (itr.hasNext()){
			String str = (String)itr.next();
			System.out.println(str+" (while) "+ht.get(str));
		}
		//利用枚举获取value
		Enumeration e = ht.elements();
		while(e.hasMoreElements()){
			System.out.println(e.nextElement());
		}
		//利用枚举获取key:value对儿
		Enumeration e2 = ht.keys();
		while(e2.hasMoreElements()){
			String key = e2.nextElement();
			System.out.println(key+" = "+ht.get(key));
		}
	}

}

你可能感兴趣的:(CoreJava,string,class)