【发布时间】:2012-04-05 12:47:37
【问题描述】:
我正在尝试为数据结构中的键存储多个值,因此我使用 Guava (Google Collection) 的 MultiMap。
Multimap<double[], double[]> destinations = HashMultimap.create();
destinations = ArrayListMultimap.create();
double[] startingPoint = new double[] {1.0, 2.0};
double[] end = new double[] {3.0, 4.0};
destinations.put(startingPoint, end);
System.out.println(destinations.containsKey(startingPoint));
它返回 false。
注意:当我将某些内容放在那里时,键值将存储在多映射中,因为 destinations.size() 会增加。当键是 String 而不是 double[] 时,也不会发生这种情况。
知道问题出在哪里吗?
编辑:非常感谢 Jon Skeet 我现在实现了这个类:
class Point {
double lat;
double lng;
public boolean equals(Point p) {
if (lat == p.lat && lng == p.lng)
return true;
else
return false;
}
@Override
public int hashCode() {
int hash = 29;
hash = hash*41 + (int)(lat * 100000);
hash = hash*41 + (int)(lng * 100000);
return hash;
}
public Point(double newlat, double newlng) {
lat = newlat;
lng = newlng;
}
}
现在我遇到了一个新问题。这就是我使用它的方式:
Multimap<Point, Point> destinations = HashMultimap.create();
destinations = ArrayListMultimap.create();
Point startingPoint = new Point(1.0, 2.0);
Point end = new Point(3.0, 4.0);
destinations.put(startingPoint, end);
System.out.println( destinations.containsKey(startingPoint) );
System.out.println( destinations.containsKey(new Point(1.0, 2.0)) );
第一个返回true,第二个返回false。如果我将@Override 放在equals 方法之前,它会给我一个错误。知道现在的问题是什么吗?
谢谢:)
Edit2:当我将 equals 更改为此时,它现在的行为与预期完全一样:
@Override
public boolean equals(Object p) {
if (this == p)
return true;
else if ( !(p instanceof Point) )
return false;
else {
Point that = (Point) p;
return (that.lat == lat) && (that.lng == lng);
}
}
谢谢大家。
【问题讨论】:
-
对于普通的 Java
Map案例有一个 related question。