Java Hash Maps / Sets Automatically transfer hash collisions, so it is important to override the equals and hashCode methods. Because both of them are used by sets to distinguish between repeating or unique entries.
It is also important to note that these hava hash collisions are performance indicators, since multiple objects are referenced by the same Hash.
public class MyObject { private String name; //getter and setters public int hashCode() { int hashCode = //Do some object specifc stuff to gen hashCode return int; } public boolean equals(Object obj) { if(this==obj) return true; if(obj instanceOf MyObject) { if(this.name.equals((MyObject)obj.getName())) { return true; } return false; } } }
Note. Standard Java objects, such as String, have already implemented hashCode and are equal, so you only need to do this for your data objects.
source share