java Hash系列(1)--散列与散列码
来源:互联网 发布:台州信息网源码 编辑:程序博客网 时间:2024/06/04 19:10
java中任何对象都继承于Object,在创建HashMap的键的类时,可能会忘记在其中放置必要的方法。
例如:一个天气预报系统,将Goundhog(土拨鼠)--key对象与Prediction(预报)对象--value联系起来。
package map;public class Groundhog { protected int number; public Groundhog(int number) { super(); this.number = number; } /**必须覆盖object中的equals和hashCode方法,否则无法用散列处理key,注意别写成了hashcode*/ /* public boolean equals(Object o) { return o instanceof Groundhog && (this.number == ((Groundhog) o).number); } public int hashCode() { return this.number; }*/ public String toString() { return "Groundhog #" + number; }}package map;import java.util.Random;public class Prediction { private static Random rand = new Random(47); private boolean shadow = rand.nextDouble() > 0.5; public String toString() { if(shadow){ return "Six more weeks of winter!"; }else{ return "Early spring!"; } } }package map;import java.lang.reflect.Constructor;import java.util.Map;import java.util.HashMap;public class SpringDetector { public static <T extends Groundhog> void detectSpring(Class<T> type) throws Exception { Constructor<T> ghog = type.getConstructor(int.class); Map<Groundhog, Prediction> map = new HashMap<Groundhog, Prediction>(); for (int i = 0; i < 10; i++) { map.put(ghog.newInstance(i), new Prediction()); } System.out.println("map=" + map); Groundhog ghog3 = new Groundhog(3); System.out.println("Looking up Prediction for " + ghog3); if (map.containsKey(ghog3)) { System.out.println(map.get(ghog3)); } else { System.out.println("key not found!"); } } public static void main(String[] args) throws Exception { detectSpring(Groundhog.class); }}
Goundhog自动继承基类Object,默认使用对象的地址计算散列码,由于反射生成第一个Goundhog(3)实例与直接生成的Goundhog(3)地址显然不相等, 因此在map查询不到这个key。
总结:要使用自己的类作为key,必须同时重载hashCode()和equals()。
0 0
- java Hash系列(1)--散列与散列码
- 查找与散列(Hash)
- 散列(hash)
- 散列(hash)
- 散列(Hash)表(1)
- 散列(Hash)目录
- hash(哈希,散列)
- 散列(Hash)基础知识
- Hash(散列函数)
- 散列:散列函数与散列表(hash table)
- 1005继续3n+1猜想(Hash散列)
- 散列(Hash table)也称哈希表
- Oracle 散列(HASH)聚簇表
- HDU-#1425 sort(Hash散列)
- 数组 链表 散列(hash)
- 散列(hash)表算法[转]
- 1029.旧键盘(Hash散列)
- 1039到底买不买(Hash散列)
- 计算机技术和通信技术紧密结合的产物
- 题目1550:分糖果
- 一个简单的Makefile示例
- Apache Hadoop 2.2.0 HDFS HA + YARN多机部署
- jquery 切换 行是否显示
- java Hash系列(1)--散列与散列码
- oracle实例内存(SGA和PGA)调整
- outlook用户密码无法保存
- libgdx——常见UI的使用
- Shell中空格、双引号与Word Splitting、Double quoting扫盲介绍
- 如何备份注册表
- oracle 查询锁表和Kill
- 2014-3-3
- 利用Double.parseDouble判断字符串是否是有效数字