set - Issue with "contains" hashset method (Java) -
the following code not giving me 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 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 be:
does pair (1, 0) exists already? false
i can't understand why it's not working. or maybe i'm using "contains" method wrong (or wrong reasons).
there issue, if add same value twice, accepted, being set
objpair.add(new pair(1, 0)); objpair.add(new pair(1, 0));
it won't accept/recognize class pair i've created?
thanks in advance.
without own hashcode() implementation, java considers 2 pair
objects equal if exact same object , new
, definition, creates 'new' object. in case, want pair
objects consider equal if have same values source
, target
-- this, need tell java how should test pair
objects equality. (and make hash maps work way expect, need generate hash code consistent equals -- loosely speaking, means equal objects must generate same hashcode, , unequal objects should generate different hash codes.
most ides generate decent hashcode() , equals() methods you. mine generated this:
@override public int hashcode() { int hash = 3; hash = 47 * hash + this.source; hash = 47 * hash + this.target; return hash; } @override public boolean equals(object obj) { if (obj == null) { return false; } if (getclass() != obj.getclass()) { return false; } final pair other = (pair) obj; if (this.source != other.source) { return false; } if (this.target != other.target) { return false; } return true; }
Comments
Post a Comment