springrolls
springrolls

Reputation: 1331

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)) {
            keyPts[0] = p1;
            keyPts[1] = p2;
            d = p1.distance(p2);
            hmDistOrd.put(keyPts, d);
        }
    }
}

Any hints? Thanks in advance!

Upvotes: 0

Views: 1505

Answers (4)

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74790

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).

Upvotes: 1

Kainsin
Kainsin

Reputation: 447

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.

Upvotes: 0

Neil
Neil

Reputation: 11

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

Upvotes: 1

Sergey Aslanov
Sergey Aslanov

Reputation: 2415

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.

Upvotes: 4

Related Questions