2

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

谢谢大家。

4

2 回答 2

8

您使用数组作为哈希键。那是行不通的——Java 不会覆盖hashCodeequals用于数组。(Arrays该类提供了执行此操作的方法,但在这里对您没有帮助。)诚然,我希望它在这种特定情况下工作,在这种情况下,您对两者使用完全相同的参考put,并且containsKey......当我测试时您的代码,它会打印true. 你确定你可以用你的代码重现它

例如,虽然我希望它适用于您提供的代码,但我希望它适用:

// Logically equal array, but distinct objects
double[] key = (double[]) startingPoint.clone();
System.out.println(destinations.containsKey(key));

听起来你不应该真的在double[]这里使用 - 你应该创建一个Point有两个double变量的类,并覆盖equalshashCode.

此外,由于二进制浮点运算的性质,double在散列键中使用值通常不是一个好主意。即使使用Point上面的想法,这也会是一个问题......如果你不需要实际做任何算术(如果你只是复制值)应该没问题,但要非常小心......

于 2012-04-05T12:51:17.067 回答
1

问题是你不能散列“相等”的数组并且每次都得到相同的结果。例如:

public static void main(String[] args) {
     System.out.println(new double[]{1.0, 2.0}.hashCode());
     System.out.println(new double[]{1.0, 2.0}.hashCode());
}

会导致类似

306344348
1211154977
于 2012-04-05T12:55:09.347 回答