HashMap是一系列的键值,使用的时候一般都是这样的<key,value>这个key一般都是字符串(而且必须是唯一的,value可以重复),那可以不可以用一个类作为key呢?
public class Groundhog {
protected int number;
public Groundhog(int number) {
this.number = number;
}
public String toString() {
return "Groundhog#" + number;
}
}
import java.util.Random;
public class Prediction {
private static Random random = new Random();
private boolean shadow = random.nextDouble() > 0.5;
public String toString() {
if(shadow) {
return "Winter";
} else {
return "Spring";
}
}
}
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class SpringDetector {
public static <T extends Groundhog> void detectSpring(Class<T> tpye)
throws NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//通过反射机制来实例化及使用Groundhog类
Constructor<T> ghog = tpye.getConstructor(int.class);
Map<Groundhog, Prediction> map = new HashMap<Groundhog, Prediction>();
for(int i = 0; i < 3; i++)
{
map.put(ghog.newInstance(i), new Prediction());
}
System.out.println("map : " + map);
/*
Groundhog gh = new Groundhog(4);
map.put(gh, new Prediction());
//这样是可以找到的,但这是以这个引用为key了,然后再通过这个引用去查找,hashcode是同一个所以可以查到
*/
//这里使用 ghog.newInstance(2)和for循环中的 ghog.newInstance(2) 是不是同一个呢?
//可以肯定的是他们的内容是相同的都是Groundhog#2。。。
Groundhog gh = ghog.newInstance(2);
System.out.println("Looking up prediction for " + gh);
if(map.containsKey(gh)) {
System.out.println(map.get(gh));
} else {
System.out.println("key not found: " + gh);
}
}
public static void main(String[] args) throws Exception{
detectSpring(Groundhog.class);
}
}
结果
map : {Groundhog#0=Winter, Groundhog#2=Spring, Groundhog#1=Spring}
Looking up prediction for Groundhog#2
key not found: Groundhog#2
代码中定义了两个类Groundhog和Prediction。后者用random实现以1/2的概率分配那两个字符串;
SpringDetector类中以Groundhog和Prediction分别作为key和value实现了一个map。其中Groundhog是以反射的方式实例化,Prediction使用new的方法。加入三个元素之后,在展示通过key来查询的效果。
其实Map用的这个key值是Groundhog中的hasCode()这个方法生成的散列值。但是Groundhog类中并没有这个方法,其实Groundhog是默认继承Object类的,既然它没有从新hasCode()方法那就说明用的是Object中的这个方法,而它默认使用对象的地址计算散列码的。因此两次newInstance(2)生成的散列码是不同的,so用后面那个是查不到前面那个的。
那是不是我们从写了hashCode()这个方法就可以了呢,其实他还是不行,还需要重新另一个方法叫equals()。因为HashMap是使用equals()来判断当前键是否与表中存在的键相同。
一下是修改后的代码加入了这两个方法。
public class Groundhog2 {
protected int number;
public Groundhog2(int number) {
this.number = number;
}
public String toString() {
return "Groundhog#" + number;
}
public int hashCode() {
return number;//用number作为hashcode,完全自己定义,能达到自己的要求即可
}
public boolean equals(Object o) {
return o instanceof Groundhog2 && (number == ((Groundhog2)o).number);//通过判断是不是Groundhog2的事例和比较number值来确定是否相等
}
}
附上书中对equals方法的5个条件
1.自反性。对任意x,x.equals(x)一定返回true;
2.对称性。对任意x和y,如果y.equals(x)返回true,则x.equals(y)也是返回true;
3.传递性。对任意的x、y、z,如果x.equals(y)返回true,y.equals(z)也返回true,则x.equals(z)一定返回true;
4.一致性。对任意x和y,如果对象中用语等价比较的信息没有改变,那么无论调用x.equals(y)多少次,返回的结果应该保持一致。
5.对任何不是null的x,x.equals(null)一定返回false。