- 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<String,String> ht = new Hashtable<String,String>();
- for(int i = 0;i<10;i++){
- ht.put("key"+i, "value"+i);
- }
- //利用循环遍历出key和value
- for(Iterator<String> 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<String> itr = ht.keySet().iterator();
- while (itr.hasNext()){
- String str = (String)itr.next();
- System.out.println(str+" (while) "+ht.get(str));
- }
- //利用枚举获取value
- Enumeration<String> e = ht.elements();
- while(e.hasMoreElements()){
- System.out.println(e.nextElement());
- }
- //利用枚举获取key:value对儿
- Enumeration<String> e2 = ht.keys();
- while(e2.hasMoreElements()){
- String key = e2.nextElement();
- System.out.println(key+" = "+ht.get(key));
- }
- }
- }
时间: 2024-12-05 21:00:14