override - Example of 2 objects in java having same hash value but equals method returns false on them -
we know if equals method returns true, 2 objects equal.
can give example 2 objects have same hash value different?
i'm assuming you're familiar contract(s) associated overriding equals() , hashcode(), , implications of collision-prone hashcode implementation. given that, following trivial example uses object holds 2 integers , implements simple hashcode, , demonstrates how easy have 2 objects aren't equal have same hashcode. providing more sophisticated hashcode algorithm can alleviate this.
the output of running main is:
hashcodes: ih1: 6, ih2: 6 equals: false example code:
package example.stackoverflow; public class intholder { private integer primarydata; private integer secondarydata; public intholder(integer primarydata, integer secondarydata) { this.primarydata = primarydata; this.secondarydata = secondarydata; } @override public int hashcode() { return ((primarydata == null) ? 0 : primarydata.hashcode()) + ((secondarydata == null) ? 0 : secondarydata.hashcode()); } @override public boolean equals(object obj) { if (this == obj) return true; if (obj == null) return false; if (getclass() != obj.getclass()) return false; intholder other = (intholder) obj; if (primarydata == null) { if (other.primarydata != null) return false; } else if (!primarydata.equals(other.primarydata)) return false; if (secondarydata == null) { if (other.secondarydata != null) return false; } else if (!secondarydata.equals(other.secondarydata)) return false; return true; } public static void main(string[] args) { intholder ih1 = new intholder(1, 5); intholder ih2 = new intholder(3, 3); system.out.println("hashcodes: ih1: " + ih1.hashcode() + ", ih2: " + ih2.hashcode()); system.out.println("equals: " + ih1.equals(ih2)); } } for reference, eclipse's auto-generated hashcode() intholder class is:
@override public int hashcode() { final int prime = 31; int result = 1; result = prime * result + ((primarydata == null) ? 0 : primarydata.hashcode()); result = prime * result + ((secondarydata == null) ? 0 : secondarydata.hashcode()); return result; }
Comments
Post a Comment