java Hashtable的遍歷方法
阿新 • • 發佈:2018-12-30
今天遇到用hashtable取值時發現取得的值是排過序的,而我並希望它排序輸出,因為它是倒序輸出,查一下原因是因為我用下面的第一種方法取值的,將hashtable的值排序輸出了,這個真是我疏忽的問題,原來hashtable還具有自動排序的功能.於是我從網上查了些資料,並整理記錄下來:
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
public class TestHashTable {
staticHashtable<String, String> ht = newHashtable<String, String>();
publicstatic void main(String[] args) {
for(int i = 0;i<100;i++){
ht.put("key"+i, "value"+i);
}
for(Iterator itr = ht.keySet().iterator();itr.hasNext();){
String key = (String) itr.next();
String value = (String) ht.get(key);
System.out.println(key+"--"+value);
}
Enumeration e1 = ht.elements();
while (e1.hasMoreElements()) {
System.out.println(e1.nextElement());
}
Enumeration e2 = ht.keys();
while (e2.hasMoreElements()) {
String key = (String) e2.nextElement();
System.out.println(key +"---"+ht.get(key));
}
}
} 如果要不按照他的hashcode排序建議用list ,Arraylist
import java.util.Hashtable;
import java.util.Iterator;
public class TestHashTable {
staticHashtable<String, String> ht = newHashtable<String, String>();
publicstatic void main(String[] args) {
for(int i = 0;i<100;i++){
ht.put("key"+i, "value"+i);
}
for(Iterator itr = ht.keySet().iterator();itr.hasNext();){
String key = (String) itr.next();
String value = (String) ht.get(key);
System.out.println(key+"--"+value);
}
Enumeration e1 = ht.elements();
while (e1.hasMoreElements()) {
System.out.println(e1.nextElement());
}
Enumeration e2 = ht.keys();
while (e2.hasMoreElements()) {
String key = (String) e2.nextElement();
System.out.println(key +"---"+ht.get(key));
}
}
} 如果要不按照他的hashcode排序建議用list ,Arraylist