hash - Java: Duplicate objects getting added to set? -
if run below code output 2 means set contains 2 elements. think set should contain 1 since both objects equal based on hashcode() value .equals()
method. seems obvious mistake in understanding ?
package hello; import java.util.hashset; import java.util.set; public class test { public static void main(string[] args) throws exception { set<alpha> s = new hashset<alpha>(); alpha a1 = new alpha(); alpha a2 = new alpha(); s.add(a1); s.add(a2); system.out.println(s.size()); } } class alpha { int = 10; public int hashcode() { return a; } public boolean equals(object obj) { return (obj instanceof alpha && ((alpha) obj).a == this.a); } public string tostring() { return "alpha : " + a; } }
your hashcode method not override object class's hashcode method , equals method breaks contract since doesn't agree hashcode results, , can have objects "equal" have different hashcodes.
remember: should use @override
annotation when overriding methods catch , similar errors.
@override // ** don't forget annotation public int hashcode() { // *** note capitalization of "c" return a; }
also, want improve code formatting, when posting code here our review. able better understand code , if conforms standards (that's why standards exist). try keep indentations consistent code lines in same block indented @ same level, , want sure base level code, including imports, outer class declarations , end curly brace, flush left:
import java.util.hashset; import java.util.set; public class test { public static void main(string[] args) throws exception { set<alpha> s = new hashset<alpha>(); alpha a1 = new alpha(); alpha a2 = new alpha(); s.add(a1); s.add(a2); system.out.println(s.size()); } } class alpha { int = 10; @override public int hashcode() { return a; } public string tostring() { return "alpha : " + a; } @override public boolean equals(object obj) { if (this == obj) return true; if (obj == null) return false; if (getclass() != obj.getclass()) return false; alpha other = (alpha) obj; if (a != other.a) return false; return true; } }
for beautiful review on this, please read: overriding equals , hashcode in java
Comments
Post a Comment