import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Vector;
public class MyDictionaryextends Dictionary {
private Vectorkeys;
private Vectorelements;
public MyDictionary() {
this.keys = new Vector();
this.elements = new Vector();
}
public Enumerationkeys() {
return this.keys.elements();
}
public Enumerationelements() {
return this.elements.elements();
}
public V get(Object key) {
int i = keys.indexOf(key);
return this.elements.get(i);
}
public boolean isEmpty() {
return this.keys.size()== 0;
}
public V put(Object key, Object value) {
int i = keys.indexOf(key);
if (i != -1) {
V oldElement = this.elements.elementAt(i);
this.elements.setElementAt((V) value, i);
return oldElement;
} else {
this.keys.addElement((K) key);
this.elements.addElement((V) value);
return null;
}
}
public V remove(Object key) {
int i = this.keys.indexOf(key);
if (i != -1) {
V oldElement = this.elements.elementAt(i);
this.keys.removeElementAt(i);
this.elements.removeElementAt(i);
return oldElement;
} else{
return null;
}
}
public int size() {
return this.keys.size();
}
/**
* @param args
*/
public static void main(String[] args) {
MyDictionarydic = new MyDictionary ();
dic.put("1", "0001");
dic.put("2", "0002");
dic.put("3", "0003");
dic.put("4", "0004");
System.out.println(dic.get("1") + " " + dic.get("2"));
System.out.println(dic.remove("2") + " " + dic.remove("4"));
Enumerationkeys = dic.keys();
while(keys.hasMoreElements()){
System.out.print(keys.nextElement() + " ");
}
System.out.println();
Enumerationelements = dic.elements();
while(elements.hasMoreElements()){
System.out.print(elements.nextElement() + " ");
}
System.out.println();
}
}
给个例子,看一下就明白了
你说的Dictionary类,是一个abstract抽象类,定义得到value的方法为:V get(Object key)。
一般利用子类类Map的实现类HashMap等,调用get(key)方法得到value。
类 HashMap ? 想自己实现一个?