《 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);
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.