Map<String, Position> map2 = new HashMap<String, Position>(); map2.put("13", new Position(2, 3)); map2.put("5", new Position(1, 2)); map2.put("17", new Position(4, 1)); map2.put("8", new Position(2, 2)); map2.put("25", new Position(3, 4)); printList(sortMap(map2));
} class Position implements Comparable<Position> { private int x; private int y; public Position(int x, int y) { this.x = x; this.y = y; }
public int distance() { return x*x + y*y; }
@Override public int compareTo(Position p) {
int thisDistance = distance(); int pDistance = p.distance();
@Override
public int compareTo(Element<K,V> e) {
try {
Method m = value.getClass().getMethod("compareTo", value.getClass());
return -((Integer) m.invoke(value, e.value));
} catch (Exception e1) {
e1.printStackTrace();
}
return 0; // dangerous! 当出现异常时,???
}这是因为,直接使用 value.compareTo(e.value) 将导致编译期的类型检查,而此时,是无法确定 V 是否拥有 compareTo() 的 方法的。因此,解决方案,就是将这种类型检查推迟到运行时。测试程序如下: public static void main(String[] args)
{
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("2", 2);
map.put("6", 6);
map.put("1", 1);
map.put("3", 3);
map.put("5", 5);
printList(sortMap(map));
Map<String, Position> map2 = new HashMap<String, Position>();
map2.put("13", new Position(2, 3));
map2.put("5", new Position(1, 2));
map2.put("17", new Position(4, 1));
map2.put("8", new Position(2, 2));
map2.put("25", new Position(3, 4));
printList(sortMap(map2));
}
class Position implements Comparable<Position> {
private int x;
private int y;
public Position(int x, int y) {
this.x = x; this.y = y;
}
public int distance() {
return x*x + y*y;
}
@Override
public int compareTo(Position p) {
int thisDistance = distance();
int pDistance = p.distance();
if (thisDistance > pDistance) {
return 1;
} else if (thisDistance < pDistance) {
return -1;
} else {
return 0;
}
}
public String toString()
{
return "[" + x + " , " + y + "]";
}
}