Hi there,
I'm trying to use a map in Java where the keys are a class of my own:
Code:
public class IntPair {
private final int x;
private final int y;
public IntPair(final int x, final int y) {
this.x = x;
this.y = y;
}
public IntPair() {
x = y = 0;
}
public int getx() { return x; }
public int gety() { return y; }
public String toString() {
return String.format("(%d,%d)",x,y);
}
} // class IntPair
Here is an example of use:
Code:
Map<IntPair,Integer> h = new HashMap<IntPair,Integer>();
IntPair r1 = new IntPair(10,2);
h.put(r1, 5);
h.put(new IntPair(10,2), 8);
h.put(new IntPair(10,2), 543);
for (IntPair r : h.keySet()) {
System.out.println(r + ":" + h.get(r));
}
So, you see, I've used three times the IntPair(10,2), hence after executing this I would like the Map to have only one element, which key the IntPair(10,2) and with value 543, but I instead of that I get three different instances, each one pointing to one different value: 5, 8 and 543.
I've tried overriding the equals method and also the hashCode() method in IntPair(), but I have had no success: I still get three elements in the Map instead of one.
Is there a way to solve this? How?
I think java is using the references/addresses for the objects to calculate the actual keys that it uses internally in the Map. The problem is that I wouldn't want to keep the references to the keys in the Map. I would like, for instance, to add new values using h.put(new IntPair(x,y)) and then being able, in another place in the program, whether new IntPair(x,y) is a key in the Map...
Thank you a lot in advance.