ArrayList custom class as HashMap key
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)) 开发者_StackOverflow社区{
keyPts[0] = p1;
keyPts[1] = p2;
d = p1.distance(p2);
hmDistOrd.put(keyPts, d);
}
}
}
Any hints? Thanks in advance!
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.
You are storing the same array instance, keyPts, into the HashMap on every iteration (and overwriting its contents as well).
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).
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.
精彩评论