Hashtable基本用法概述
Hashtable-哈希表類(lèi)
以哈希表的形式存儲(chǔ)數(shù)據(jù),數(shù)據(jù)的形式是鍵值對(duì).
特點(diǎn):
查找速度快,遍歷相對(duì)慢
鍵值不能有空指針和重復(fù)數(shù)據(jù)
創(chuàng)建
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
添值
ht.put(1,"Andy");
ht.put(2,"Bill");
ht.put(3,"Cindy");
ht.put(4,"Dell");
ht.put(5,"Felex");
ht.put(6,"Edinburg");
ht.put(7,"Green");
取值
String str=ht.get(1);
System.out.println(str);// Andy
對(duì)鍵進(jìn)行遍歷
Iterator it = ht.keySet().iterator();
while (it.hasNext()) {
Integer key = (Integer)it.next();
System.out.println(key);
}
對(duì)值進(jìn)行遍歷
Iterator it = ht.values().iterator();
while (it.hasNext()) {
String value =(String) it.next();
System.out.println(value);
}
取Hashtable記錄數(shù)
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
ht.put(1,"Andy");
ht.put(2,"Bill");
ht.put(3,"Cindy");
ht.put(4,"Dell");
ht.put(5,"Felex");
ht.put(6,"Edinburg");
ht.put(7,"Green");
int i=ht.size();// 7
刪除元素
Hashtable<Integer,String> ht=new Hashtable<Integer,String>();
ht.put(1,"Andy");
ht.put(2,"Bill");
ht.put(3,"Cindy");
ht.put(4,"Dell");
ht.put(5,"Felex");
ht.put(6,"Edinburg");
ht.put(7,"Green");
ht.remove(1);
ht.remove(2);
ht.remove(3);
ht.remove(4);
System.out.println(ht.size());// 3
Iterator it = ht.values().iterator();
while (it.hasNext()) {
// Get value
String value =(String) it.next();
System.out.println(value);
}
輸出:
3
Green
Edinburg
Felex
posted on 2008-02-21 19:20 和風(fēng)細(xì)雨 閱讀(13866) 評(píng)論(2) 編輯 收藏 所屬分類(lèi): J2SE