i executed below code , found output false.
import java.util.set; import java.util.hashset; public class name { private string first, last; public name(string first, string last) { this.first = first; this.last = last; } public boolean equals(object o) { if (!(o instanceof name)) return false; name n = (name) o; return n.first.equals(first) && n.last.equals(last); } public static void main(string[] args) { set<name> s = new hashset<name>(); s.add(new name("donald", "duck")); system.out.println(s.contains(new name("donald", "duck"))); } } i want know how behaves , why output false.
you need override hashcode() method along equals(). both methods used proper functionality of hashset, must overriden in user-defined class if making class key, else hashcode() of object class getting used , no 2 different objects can considered same hashcode() different, , sure return falsealways in case of contains().
Comments
Post a Comment