package ming; import java.util.Hashtable; class D { int count; public D(int count) { this.count = count; } public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj.getClass() == D.class) { D d = (D) obj; return this.count == d.count; } return false; } public int hashCode(){ return this.count; } } class E{ @Override public boolean equals(Object obj) { return true; } } public class HashtableTest { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Hashtable ht = new Hashtable(); ht.put(new D(6000), "java"); ht.put(new D(87563), "C++"); ht.put(new D(1232), new E()); System.out.println(ht); /*只要equals方法返回true * Hashtable就认为他们是相等的value * Hashtable有一个对象E对象 * 它与任何对象通过equal方法比较都相等,所以下面输出是true */ System.out.println(ht.containsValue("testing value")); /* * 只要D两个对象的count相等,通过equals()方法比较返回true,且hashcode相等 * Hashtable就认为它们相等,所以下面返回true * */ System.out.println(ht.containsValue(new D(6000))); /* * 删除最后一个key-value * */ ht.remove(new D(1232)); /* * 遍历所有的key-value * */ for(Object key:ht.keySet()){ System.out.print(key+"-->"); System.out.print(ht.get(key)); System.out.println(); } } }
//不要修改key的值!!!!!!!!!!!!!!!!!!!!!!!!!!