Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.
It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
Note that it is generally necessary to override the hashCode method
whenever this method is overridden, so as to maintain the general
hashCode方法的合同,该方法声明相等的对象必须
有相同的哈希码。
由 Object 类定义的 hashCode 方法尽可能实用
return distinct integers for distinct objects. (This is typically implemented by
converting the internal address of the object into an integer, but this implementation
JavaTM 编程语言并不需要这种技术。)
但是,有时您希望具有相同含义的不同对象的哈希代码是相同的。比如说
Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode
如果在集合框架(如 HashTable、 HashSet)中使用哈希数据结构,就会出现这种问题。特别是像 HashSet 这样的集合,你最终会有重复的元素并且违反 Set 协议。