个人博客:skyfffire.cn

Hashtable的hashCode的使用以及toString的复写——《Thinking in Java》随笔024

 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:13
11 */
12 class Groundhog2 {
13     int ghNumber;
14     
15     Groundhog2(int n) {
16         ghNumber = n;
17     }
18     
19     // Hashtable的get方法要使用这个方法
20     @Override
21     public int hashCode() {
22         return ghNumber;
23     }
24     
25     // HashTable的containsKey要使用
26     @Override
27     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的toString
36         Hashtable<Groundhog2, Prediction> ht = 
37                 new Hashtable<Groundhog2, Prediction>() {
38                     private static final long serialVersionUID = -8222553412985239408L;
39 
40                     @Override
41                     public String toString() {
42                         String str = "";
43                         Enumeration<Groundhog2> 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 ///:~

 

posted @ 2017-03-14 20:10  skyfffire  阅读(140)  评论(0编辑  收藏  举报
个人博客:skyfffire.cn