The following code is not giving me the result I'm expecting:
public static void main (String[] args) {
Set<Pair> objPair = new LinkedHashSet<Pair>();
objPair.add(new Pair(1, 0));
System.out.println("Does the pair (1, 0) exists already? "+objPair.contains(new Pair(1, 0)));
}
private static class Pair {
private int source;
private int target;
public Pair(int source, int target) {
this.source = source;
this.target = target;
}
}
The result will be:
Does the pair (1, 0) exists already? false
I can't understand why it's not working. Or maybe I'm using the "contains" method wrong (or for the wrong reasons).
There is also another issue, if I add the same value twice, it will be accepted, even being a set
objPair.add(new Pair(1, 0));
objPair.add(new Pair(1, 0));
It won't accept/recognize the class Pair I've created?
Thanks in Advance.
Without your own hashCode() implementation, Java considers two
Pair
objects equal only if they are the exact same object andnew
, by definition, always creates a 'new' object. In your case, you wantPair
objects to be consider equal if they have the same values forsource
andtarget
-- to do this, you need to tell Java how it should testPair
objects for equality. (and to make hash maps work the way you expect, you also need to generate a hash code that is consistent with equals -- loosely speaking, that means equal objects must generate the same hashCode, and unequal objects should generate different hash codes.Most IDEs will generate decent hashcode() and equals() methods for you. Mine generated this:
You need to override your
hashCode
andequals
methods in yourPair
class.LinkedHashSet
(and other Java objects that use hash codes) will use them to locate and find yourPair
objects.