Overriding hashcode and equals in java -
i unclear use of hashcode , equals method in java.i have following query
first
if override equals method objects of value fred added though hashset implements set interface,which cant take repeated values.
second if override both equals , hashcode 1 object added hashset.why?
third if implement equals in case removing 1 fred object remove all?
class person { string name; person(string name) { this.name=name; } @override public boolean equals(object obj) { if(!(obj instanceof person)) { return false; } person p = (person)obj; return p.name.equals(this.name); } /*@override public int hashcode() { return name.hashcode(); }*/ } public class hashsetdemo { /* * @param args */ public static void main(string[] args) { // todo auto-generated method stub hashset<person> s= new hashset<person>(); s.add(new person("fred")); s.add(new person("fred")); s.add(new person("fred")); s.add(new person("fred1")); for(person a:s) { system.out.println(a.name); } s.remove(new person("fred")); system.out.println(s); } }
from "effective java" joshua bloch, item 9:
you must override
hashcode
in every class overridesequals
. failure result in violation of general contractobject.hashcode
, prevent class functioning in conjunction hash-based collections, includinghashmap
,hashset
, ,hashtable
.
the eclipse ide generate hashcode
, equals
method you.
most hashcode
methods this:
public int hashcode() { int result = 17; result = 31 * result + field1; (int) result = 31 * result + field2.hashcode(); (object) ... rest of fields. return result; }
Comments
Post a Comment