/**
* 书本:《Thinking In Java》
* 功能:散列与散列码
* 文件:Groundhog.java
* 时间:2015年5月3日09:42:54
* 作者:cutter_point
*/
package Lesson17Containers;
public class Groundhog
{
protected int number;//保护类型,继承之后还是保护类型
public Groundhog(int n) { number = n; }
public String toString()
{
return "Groundhog #" + number;
}
}
/**
* 书本:《Thinking In Java》
* 功能:散列与散列码
* 文件:Prediction.java
* 时间:2015年5月3日09:42:54
* 作者:cutter_point
*/
package Lesson17Containers;
import java.util.Random;
public class Prediction
{
private static Random rand = new Random(47);
private boolean shadow = rand.nextDouble() > 0.5;//判断产生的数值的范围,nextDouble产生的值在0到1之间
public String toString()
{
if(shadow)
return "Six more weeks of Winter!";
else
return "Early Spring!";
}
}
/**
* 书本:《Thinking In Java》
* 功能:散列与散列码,一个天气预报系统,将Groundhog和Prediction对象联系起来
* 文件:SpringDeterctor.java
* 时间:2015年5月3日09:42:54
* 作者:cutter_point
*/
package Lesson17Containers;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import static net.mindview.util.Print.*;
public class SpringDeterctor
{
public static void detectSpring(Class type) throws Exception
{
Constructor ghog = type.getConstructor(int.class);//获取type中参数是Int的构造器,这个是反射
Map map = new HashMap();
for(int i = 0; i < 10; ++i)
{
//初始化map里面的值,第二个参数是随机产生的两种状况
map.put(ghog.newInstance(i), new Prediction());
}
print("map = " + map);
Groundhog gh = ghog.newInstance(3);
print("Looking up prediction for " + gh);
if(map.containsKey(gh))//等会我们发现找不到3号
print(map.get(gh));
else
print("Key not found: " + gh);
}
public static void main(String[] args) throws Exception
{
detectSpring(Groundhog.class);
}
}
输出:
map = {Groundhog #9=Six more weeks of Winter!, Groundhog #4=Six more weeks of Winter!, Groundhog #2=Early Spring!, Groundhog #7=Early Spring!, Groundhog #8=Six more weeks of Winter!, Groundhog #3=Early Spring!, Groundhog #1=Six more weeks of Winter!, Groundhog #6=Early Spring!, Groundhog #5=Early Spring!, Groundhog #0=Six more weeks of Winter!} obj1
Looking up prediction for Groundhog #3 obj1
Key not found: Groundhog #3 obj1
/* * 无法找到3号原因: * 问题出现在Groundhog自动继承基类Object,所以这里使用Object的hashCode方法生成散列码,而他默认的是使用对象的地址计算散列码, * 因此,由Groundhog(3)生成的第一个实例的散列码和由Groundhog gh = ghog.newInstance(3);生成的第二个实例散列码是不同的 * 而我们是按后者进行查找的 * * 解决: * 只编写hashCode的方法的覆盖方法还是无法运行,除非你同时覆盖equals */