zoukankan      html  css  js  c++  java
  • 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) + "
    ");
    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 ///:~
  • 相关阅读:
    安装python包的两种方法
    Oracle 查询当前用户下的所有表
    Oracle SQL存储过程结构、异常处理示例
    Oracle IF-ELSE条件判断结构
    Oracle 组函数count()
    从svn下载项目后出现 Error:java: Compilation failed: internaljava compiler error 解决办法
    当学习失去方向,开始荒废时光时
    给自己一个目标
    汇编环境搭建在Linux下
    汇编学习总结
  • 原文地址:https://www.cnblogs.com/skyfffire/p/6550430.html
Copyright © 2011-2022 走看看