【ThinkingInJava】51、散列與散列碼,thinkinginjava51
/*** 書本:《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!";elsereturn "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 <T extends Groundhog> void detectSpring(Class<T> type) throws Exception{Constructor<T> ghog = type.getConstructor(int.class);//擷取type中參數是Int的構造器,這個是反射Map<Groundhog, Prediction> map = new HashMap<Groundhog, Prediction>();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
*/