ArrayList custom class as HashMap key

北城以北 提交于 2019-12-25 00:43:16

问题


I want to store my data in HashMap<Point[], Double>. I used iteration to assign the data, but when I checked at the end, the number of elements is only 1. I have implemented hashCode() and equals() in the custom class Point.

HashMap<Point[], Double> hmDistOrd = new HashMap<Point[], Double>();
Point[] keyPts = new Point[2];

for (int i=0; i<intersectionPts.size(); i++) {
p1 = intersectionPts.get(i);
    for (int j=0; j<intersectionPts.size(); j++) {
        p2 = intersectionPts.get(j);                
        if (!p1.equals(p2)) {
            keyPts[0] = p1;
            keyPts[1] = p2;
            d = p1.distance(p2);
            hmDistOrd.put(keyPts, d);
        }
    }
}

Any hints? Thanks in advance!


回答1:


You can't use array as a key, as array has default implementation of hashCode and equals from Objects and it doesn't consider it's elements.

To make it work you had to override hashCode and equals of array, but you can't do it.

You can use ArrayList instead, as it implements hashCode end equals comparing elements.




回答2:


You are storing the same array instance, keyPts, into the HashMap on every iteration (and overwriting its contents as well).




回答3:


As Jim said in his (deleted) answer, you are putting the same key object several times in the map, which will result in replacing the previous value.

But putting a new array for each element will not be better, either - then you will have more key-value-pairs, but you can't access them via the get method, if you don't have the right array object (and then you could have the value, too), as arrays do not implement .equals and hashCode.

To propose a solution: You could use an List<Point> as your key type, and use a new list for each pair of key points. Make sure you don't modify the list after putting it as a key into the map. (You can wrap it by Collections.unmodifiableList to make sure of this.)

An alternative would be some custom pair-of-points class (with it own hashCode and equals implementation).




回答4:


When you use an array as the key for a hash map it is that array's hashCode method that is used to determine the key's hash and not your Point class.

For your specific case I would try using a map of maps: Map<Point, Map<Point, Double>> or a custom 2D matrix class with 2 keys and a value.



来源:https://stackoverflow.com/questions/6775478/arraylist-custom-class-as-hashmap-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!