我正在尝试在数据结构中存储一个键的多个值,所以我使用 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);
}
}
谢谢大家。