一>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
原文:http://www.cnblogs.com/harry0906/p/3662723.html