Java HashTable遍历的2钟方法

1. for循环遍历

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);
}

2. Enumeration对象遍历

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());
}

版权声明:本文为JAVASCHOOL原创文章,未经本站允许不得转载。