java遍历Hashmap/Hashtable的几种方法

一>java遍历Hashtabe:

import java.util.Hashtable;
import java.util.Set;

public class HashTableTest {

	public static void main(String args[]){
		Hashtable<String, String> ht = new Hashtable<String, String>();
		ht.put("one", "The first");
		ht.put("two", "The second");
		ht.put("three", "The third");
		Set<String> s = ht.keySet();
		for(String ss:s){
			System.out.println("Current hashtable element is: " + ss);
		}
	}
}

  对象的遍历:

Person person1=new Person("zhangsan",20);
Person person2=new Person("lisi",21);
Person person3=new Person("wangwu",22);
Hashtable ht = new Hashtable();//不能Map ht=new Hashtable();若加强制转换后,后面方法不能用
ht.put("first", person1);
ht.put("second", person2);
ht.put("three", person3);
Enumeration e=ht.elements();
while(e.hasMoreElements()){
  Person person=(Person)e.nextElement();
  System.out.println(person.getName()+" "+person.getAge());
 } 

 

二>java遍历Hashmap:

      第一种方法.据说效率高

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class HashMapTest {

    public static void main(String args[]){
          Map map = new HashMap();
          map.put("Fruit1", "Apple");
          map.put("Fruit2", "Orange");
          map.put("Fruit3", "Pear");
            
          Iterator it = map.entrySet().iterator();
          while(it.hasNext()){
              Map.Entry entry = (Map.Entry)it.next();
	      Object key = entry.getKey();
              Object value = entry.getValue();
              System.out.println("Map key: " + key + " " + "Map value: " + value);
          }
    }
}

  

   第二种方法:

Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
  Object key = iter.next();
  Object val = map.get(key);
}

  

posted @ 2014-04-13 20:46  harry0906  Views(386)  Comments(0)    收藏  举报