首页 > 编程语言 > 详细

java遍历Hashmap/Hashtable的几种方法

时间:2014-04-14 05:07:17      阅读:624      评论:0      收藏:0      [点我收藏+]

一>java遍历Hashtabe:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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);
        }
    }
}

  对象的遍历:

1
2
3
4
5
6
7
8
9
10
11
12
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:

      第一种方法.据说效率高

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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);
          }
    }
}

  

   第二种方法:

1
2
3
4
5
6
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
  Object key = iter.next();
  Object val = map.get(key);
}

  

java遍历Hashmap/Hashtable的几种方法,布布扣,bubuko.com

java遍历Hashmap/Hashtable的几种方法

原文:http://www.cnblogs.com/harry0906/p/3662723.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!