博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Hashtable的hashCode的使用以及toString的复写——《Thinking in Java》随笔024
阅读量:4699 次
发布时间:2019-06-09

本文共 2155 字,大约阅读时间需要 7 分钟。

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         Hashtable
ht = 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 ///:~

 

转载于:https://www.cnblogs.com/skyfffire/p/6550430.html

你可能感兴趣的文章
android多层树形结构列表学习笔记
查看>>
Android_去掉EditText控件周围橙色高亮区域
查看>>
《构建之法》第一、二、十六章阅读笔记
查看>>
arrow:让Python的日期与时间变的更好
查看>>
(转)Excel的 OleDb 连接串的格式(连接Excel 2003-2013)
查看>>
Java并发编程
查看>>
Git Stash用法
查看>>
sql server 2008学习8 sql server存储和索引结构
查看>>
Jquery radio选中
查看>>
memcached 细究(三)
查看>>
RSA System.Security.Cryptography.CryptographicException
查看>>
webservice整合spring cxf
查看>>
[解题报告] 100 - The 3n + 1 problem
查看>>
Entity Framework 学习高级篇1—改善EF代码的方法(上)
查看>>
Mybatis逆向工程配置文件详细介绍(转)
查看>>
String类的深入学习与理解
查看>>
不把DB放进容器的理由
查看>>
OnePage收集
查看>>
Java parseInt()方法
查看>>
yahoo的30条优化规则
查看>>