
《 Thinking in Java 》的 Containers in Depth 一章的 Hashing and hash codes 有这么一段演示代码: 一个天气系统,将 Groundhog (土拨鼠)对象和 Prediction (预报)对象联系起来。
代码本身很简单,但是看的时候是不是一脸懵逼?( ̄д ̄;)ノ为什么土拨鼠和天气预报有关?
土拨鼠日(英语:Groundhog Day ),是北美地区的一个传统节日。每年 2 月 2 日,美国和加拿大许多城市和村庄都会庆祝。自从 1887 年以来,一代又一代的土拨鼠一直担着预报时令的任务。根据传说,如果土拨鼠能看到它自己的影子,那么北美的冬天还有 6 个星期才会结束。如果它看不到影子,春天不久就会来临。-----摘自维基百科
俏丽奶奶_
最后推荐下《土拨鼠之日》这部电影(°°)
//: containers/Groundhog.java // Looks plausible, but doesn ’ t work as a HashMap key. public class Groundhog { protected int number; public Groundhog(int n) { number = n; } public String toString() { return "Groundhog #" + number; } } ///:~ //: containers/Prediction.java // Predicting the weather with groundhogs. import java.util.*; 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!"; } } ///:~ //: containers/SpringDetector.java // What will the weather be? import java.lang.reflect.*; import java.util.*; import static net.mindview.util.Print.*; public class SpringDetector { // Uses a Groundhog or class derived from Groundhog: 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()); print("map = " + map); Groundhog gh = ghog.newInstance(3); print("Looking up prediction for " + gh); if(map.containsKey(gh)) print(map.get(gh)); else print("Key not found: " + gh); } public static void main(String[] args) throws Exception { detectSpring(Groundhog.class); 1 anguslg 2018 年 1 月 29 日 我是在看完<源代码>和<明日边缘>之后看的<土拨鼠之日>, 看到你的标题我第一想到的就是这个电影 |
2 taisenjay 2018 年 1 月 29 日 涨了一波知识,666 |
3 sandao OP @anguslg 我也是诶,源代码我记得我还是高中跑去学校一个人把投影仪打开看的,当时觉得除了男演员其他演员都好省事(°°) |
4 jerry12547 2018 年 1 月 29 日 这个前几天我在知乎上看到过,他们还养着那个土拨鼠来着,然后市长还会过来庆祝。。 |
5 pusidun 2018 年 1 月 29 日 不是说,有一次土拨鼠预测错了,还被起诉了? |
6 QAPTEAWH 2018 年 1 月 29 日 土拨鼠:啊~~~~~~ |
7 imn1 2018 年 1 月 29 日 土拨鼠:None of my businese ! |
9 ReVanTis 2018 年 1 月 29 日 土拨鼠发来贺电 |
12 paloalto 2018 年 1 月 29 日 |