我试图在数据结构中存储一个密钥的多个值,所以我使用的是Guava(Google集合)的MultiMap。Java 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。
注意:键值存储在multimap中,因为destinations.size()
在我放置某些东西时增加。当键为String
而不是double[]
时,也不会发生键值。
任何想法是什么问题?
编辑:非常感谢乔恩斯基特我现在实现的类:
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);
}
}
谢谢大家。
有一个[相关问题](http://stackoverflow.com/questions/16839182/can-a-java-array-be- used-as-a-hashmap-key)用于普通Java“Map”情况。 – Raedwald 2015-02-26 12:57:39