Concept
What is the relationship between equals() and hashCode()?
ComputerScienceOne / Composition
"Objects if two instances are equal (that is, equals() returns true) then they must have the same hashCode() value. This requirement is necessary to ensure that hash table-based data structures operate properly. It is okay if unequal objects have equal or unequal hash values. This rule only applies when the objects are equal.\n\n1 public int hashCode() {\n\n2 final int prime = 31;\n\n3 int result = 1;\n\n4 result = prime * result + ((firstName == null) ? 0 :\n\n5 firstName.hashCode());\n\n6 long temp;\n\n7 temp = Double.doubleToLongBits(gpa);\n\n8 result = prime * result + (int) (temp ^ (temp >>> 32));\n\n9 result = prime * result + ((lastName == null) ? 0 :\n\n10 lastName.hashCode());\n\n11 result = prime * result + nuid;\n\n12 return result;\n\n13 }"
Related Ideas
- How do equals() and hashCode() define object equality in Java?ComputerScienceOne · Common Methods
- Why are equals() and hashCode() important when searching and using sets?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- What does the completed Java Student class example contain?ComputerScienceOne · Example
- What common methods do Java classes inherit?ComputerScienceOne · Usage
- How can the toString() method represent a Java object?ComputerScienceOne · Common Methods