Hashtable的使用方法介绍


1*****************************************************************
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Vector;

@SuppressWarnings("rawtypes")
public class HashTable1 extends Dictionary{ //Dictionary是个什么东东?

private Vector keys = new Vector();
private Vector values = new Vector();

@Override
public Enumeration elements() {
return values.elements();
}

@Override
public Object get(Object key) {
int index = keys.indexOf(key);
if(index == -1){
return null;
}
return values.elementAt(index);
}

@Override
public boolean isEmpty() {
return keys.isEmpty();
}

@Override
public Enumeration keys() {
return keys.elements();
}

@SuppressWarnings("unchecked")
@Override
public Object put(Object key, Object value) {
keys.addElement(key);
values.addElement(value);
return key;
}

@Override
public Object remove(Object key) {
int index = keys.indexOf(key);
if(index == -1){
return null;
}
keys.removeElementAt(index);
Object returnval = values.elementAt(index);
values.removeElementAt(index);
return returnval;
}

@Override
public int size() {
return keys.size();
}

public static void main(String are[]){
HashTable1 ht = new HashTable1();
for(char c = 'a' ;c <= 'z';c++){
ht.put(String.valueOf(c), String.valueOf(c).toUpperCase());
}
char [] ca = {'a','e','i','o','u'};
for(int i=0;i<ca.length;i++){
System.out.println("Uppercase: "+ht.get(String.valueOf(ca[i])));
}
}
}
//Vector 具有的方法:size() removeElementAt() addElement() elements() get()
// indexOf() elementAt() 等等


2***********************************************************************
import java.util.Hashtable;

class Counter{
int i=1;
public String toString(){
return Integer.toString(i);
}
}
public class HashTable2 {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String args[]){
Hashtable ht = new Hashtable();
for(int i=0;i<1000;i++){
Integer r = new Integer((int)(Math.random()*20));
if(ht.containsKey(r)){
((Counter)ht.get(r)).i++;
}else{
ht.put(r, new Counter());
}
}
System.out.println(ht);
}
}

*******************************************************************
import java.util.*;

public class HashtableTest_1 {

public static void main(String[] args) {

Hashtable<String, String> hh = new Hashtable<String, String>();
hh.put("a", "name"); // 姓名
hh.put("b", "age"); // 年龄
hh.put("c", "address"); // 地址
hh.put("d", "wage"); // 工资

Enumeration<String> er = hh.keys();//返回此哈希表中的键的枚举
while (er.hasMoreElements()) {//判断此枚举是否包含更多的元素。
Object o = er.nextElement();//返回此枚举的下一个元素,也就是key值
Object v = hh.get(o); //根据key将 value取出
System.out.println(o + "=" + v);
}

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值