1 //: SpringDetector2.java 2 package cn.skyfffire; 3 4 import java.util.Enumeration; 5 import java.util.Hashtable; 6 7 /** 8 * @user: skyfffire 9 * @data: 2017年3月14日 10 * @time: 下午6:31:1311 */12 class Groundhog2 {13 int ghNumber;14 15 Groundhog2(int n) {16 ghNumber = n;17 }18 19 // Hashtable的get方法要使用这个方法20 @Override21 public int hashCode() {22 return ghNumber;23 }24 25 // HashTable的containsKey要使用26 @Override27 public boolean equals(Object o) {28 return (o instanceof Groundhog2) 29 && (ghNumber == ((Groundhog2)o).ghNumber);30 }31 }32 33 public class SpringDetector2 {34 public static void main(String[] args) {35 // 为了方便查看其中的键值对,复写了Hashtable的toString36 Hashtableht = 37 new Hashtable () {38 private static final long serialVersionUID = -8222553412985239408L;39 40 @Override41 public String toString() {42 String str = "";43 Enumeration ge = this.keys();44 45 while (ge.hasMoreElements()) {46 Groundhog2 gh2 = ge.nextElement();47 48 str += (gh2 + " = " + this.get(gh2) + "\n");49 }50 51 return str;52 }53 };54 55 // 添加十个键值对56 for (int i = 0; i < 10; i++) {57 ht.put(new Groundhog2(i), new Prediction());58 }59 60 // 查看键值对中的内容61 System.out.println(ht.toString());62 System.out.println(63 "Looking up prediction for groundhog #3:");64 65 // 复写了hashCode之后可以方便地比较ghNumber相同的键66 Groundhog2 hg = new Groundhog2(3);67 68 if (ht.containsKey(hg)) {69 System.out.println((Prediction)ht.get(hg));70 }71 }72 }73 74 ///:~