When customizing equals() and hashCode() in Java, ensure that if both objects are deemed equal according to equals(), their hashCode() values should also be identical, maintaining the contract for hash-based collections.
This article will explore the equals() and hashCode() methods in Java, along with the challenges one might encounter when overriding them.
The equals() method, by default, evaluates the object references of the two instances, but when overridden, it examines their field values. It returns true if both instances refer to the identical memory location and false otherwise.
Syntax:
public boolean equals (Object obj)
Example:
Java
Code Copied!
var isMobile = window.innerWidth “);
editor31500.setValue(decodedContent); // Set the default text
editor31500.clearSelection();
editor31500.setOptions({
maxLines: Infinity
});
function decodeHTML31500(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard31500() {
const code = editor31500.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
data: {
language: “java”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
var myArray = response.split(“~”);
var data = myArray[1];
jQuery(“.output31500”).html(“
"+data+"");
jQuery(".maineditor31500 .code-editor-output").show();
jQuery("#runBtn31500 i.run-code").hide();
}
})
}
function closeoutput31500() {
var code = editor31500.getSession().getValue();
jQuery(".maineditor31500 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn31500").addEventListener("click", copyCodeToClipboard31500);
document.getElementById("runBtn31500").addEventListener("click", runCode31500);
document.getElementById("closeoutputBtn31500").addEventListener("click", closeoutput31500);
Output:
Clarification: In the sample code, three instances are created. Here, obj1 and obj2 have different object references, leading to an output of false during comparison. In contrast, obj1 and obj3 have the same memory location, resulting in a true output.
The hashCode() function in Java yields an integer value that assists in identifying objects within hash-based collections such as HashMap or HashSet.
The hashCode() value does not need to be unique for every object. However, the standard implementation generally returns a hash based on the object’s memory address. The value is calculated upon calling the method, not during the object's creation.
function closeoutput18453() {
var code = editor18453.getSession().getValue();
jQuery(".maineditor18453 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn18453").addEventListener("click", copyCodeToClipboard18453);
document.getElementById("runBtn18453").addEventListener("click", runCode18453);
document.getElementById("closeoutputBtn18453").addEventListener("click", closeoutput18453);
Output:
Clarification: In the aforementioned code, obj1 and obj2 generate distinct values from the hashCode() method since both objects are located in different memory spaces.
Note: These functions are present in the java.lang.Object package.
What Considerations should be taken when overriding equals and hashCode in Java?
Consideration 1: Overriding both equals() and hashCode() functions
When two objects are identical, the hashCode function will produce the same value for both.
When the hashCode function is invoked multiple times on the same object during a single run, it must return the same integer value. This value should remain constant from one execution of the application to the next.
It is not mandatory that when two objects are not equal according to the equals(java.lang.Object) function, invoking the hashCode function on both objects should result in different integer values. Thus, generating different integer values for unequal objects can enhance the efficiency of hash tables.
Overriding the equals() method without also overriding hashCode() can lead to the creation of two distinct hashCode values for identical objects, which breaches the hashCode contract.
If the equals() method is overridden but hashCode() is not, two equivalent objects could be perceived as different within hash-based collections, resulting in unexpected behaviors, such as duplicate entries or unsuccessful retrieval of stored objects.
It’s important to note that if the class object is not utilized in any hash-based collections, then whether hashCode() is overridden or not is irrelevant.
Example:
Java
Code Copied!
var isMobile = window.innerWidth
“““javascript
“);
editor45078.setValue(decodedContent); // Establish the default text
editor45078.clearSelection();
editor45078.setOptions({
maxLines: Infinity
});
function decodeHTML45078(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to transfer code to clipboard
function copyCodeToClipboard45078() {
const code = editor45078.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
function closeoutput45078() {
var code = editor45078.getSession().getValue();
jQuery(".maineditor45078 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn45078").addEventListener("click", copyCodeToClipboard45078);
document.getElementById("runBtn45078").addEventListener("click", runCode45078);
document.getElementById("closeoutputBtn45078").addEventListener("click", closeoutput45078);
Output:
Issue 3: Overriding the hashCode() method
If only the hashCode() method is overridden, both objects will map to the same bucket since they will share the same hashCode.
However, since the equals method remains unaltered, it will check for an existing object; if found, that instance will be returned; if not, a new instance will be added to the collection, even if it is logically equivalent to another.
This situation may result in duplicate instances in HashSet or erroneous key retrievals in HashMap, which contravenes the anticipated functionality of hash-based collections.
Example:
Java
Code Copied!
var isMobile = window.innerWidth “);
editor48277.setValue(decodedContent); // Establish the default text
editor48277.clearSelection();
editor48277.setOptions({
maxLines: Infinity
});
function decodeHTML48277(input) {
var doc = new DOMParser().parseFromString(input, “text/html”);
return doc.documentElement.textContent;
}
// Function to transfer code to clipboard
function copyCodeToClipboard48277() {
const code = editor48277.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert(“Code copied to clipboard!”);
data: {
language: “java”,
code: code,
cmd_line_args: “”,
variablenames: “”,
action:”compilerajax”
},
success: function(response) {
// Add successful response handling here
}
});
“““javascript
function(response) {
var myArray = response.split(“”~””);
var data = myArray[1];
jQuery(“”.output48277″”).html(“<pre>”” + data + “”</pre>”);
jQuery(“”.maineditor48277 .code-editor-output””).show();
jQuery(“”#runBtn48277 i.run-code””).hide();
}
function closeoutput48277() {
var code = editor48277.getSession().getValue();
jQuery(“”.maineditor48277 .code-editor-output””).hide();
}
// Bind events to the buttons
document.getElementById(“”copyBtn48277″”).addEventListener(“”click””, copyCodeToClipboard48277);
document.getElementById(“”runBtn48277″”).addEventListener(“”click””, runCode48277);
document.getElementById(“”closeoutputBtn48277″”).addEventListener(“”click””, closeoutput48277);
Output:
When and why is it necessary to override the equals() and hashCode() methods in Java?
One should override the equals() and hashCode() methods in Java when it is desired to assess object equivalence based on their content rather than their memory address, particularly when placing them in collections such as HashSet, HashMap, or Hashtable.
Hash codes influence how objects are allocated into buckets within hash-based data structures, though they do not dictate the actual memory address of the object.
Altering equals() guarantees that objects with matching content are regarded as equal. If you merely override equals(), hash-based collections may misidentify duplicates, resulting in unforeseen consequences.
In a similar vein, if only hashCode() is overridden without altering equals(), then objects sharing the same hash code could be deemed unequal since equals() retains its default reference equality.
Best Practices for Overriding equals() and hashCode() in Java
1. Override Both Methods Together to Prevent Unexpected Issues Overriding solely one of the methods, either equals() or hashCode(), can result in unpredictable behavior when working with collections like HashMap, HashSet, and Hashtable.
2. Access Properties in a Manner that Maintains Encapsulation and Sidesteps Side Effects. Avoid directly altering or accessing the variables. Utilize Getters and Setters, as they govern how the data will be accessed or modified, thereby preserving the class integrity.
3. Use instanceof Before Assessing Object Equivalence Prior to comparison, employ the instanceof operator to ensure that the object being compared is of the appropriate type. This will avert ClassCastException.
4. Adhere to the Contract of Both Methods Java lays out certain guidelines for the equals() and hashCode() methods:
Equals Contract:
Reflexive: x.equals(x) should return true.
Symmetric: If x.equals(y) is true, then y.equals(x) should also be true.
Transitive: If x.equals(y) and y.equals(z), then x.equals(z) must also be true.
Consistent: If x.equals(y) is true at one point, it should remain true unless modified.
Null-safety: x.equals(null) should return false.
Hashcode Contract:
If two objects are considered equal (i.e., equals() returns true), their hashCode() values must also be identical.
If two objects differ, their hashCode() values should also differ, enhancing the performance of hash-based collections.
The hashCode() method ought to consistently return the same value for an object.
5. Consistency with equals() For any two objects that are deemed equal, their hashCode() should invariably yield the same value.
6. Performance An effective hashCode() will evenly distribute objects within hash tables, thus expediting operations like addition, deletion, or retrieval.
7. Immutability
Avoid altering the values while employing hashCode(), as modifying values may lead to errors.
8. Relevant Fields
Only incorporate the fields that are significant for equality to ensure efficiency.
9. Null Management Ensure that both methods properly manage null values to prevent errors.
10. Consistency Both methods should return the same value every time they are invoked, until alterations to the object occur.
Conclusion
Overriding both the equals() and hashCode() methods is crucial for ensuring accurate behavior when comparing objects based on their values, such as in HashSet or HashMap. The equals() method assists in verifying if objects are equivalent, while hashCode() facilitates their correct storage. It is advisable to override both methods together to avert complications like duplicate entries. Utilizing getter methods and validating object types can aid in maintaining the functionality of the code.
To expand your knowledge about Java, you may refer to our Java Course.
What Considerations Should be Taken When Overriding equals and hashCode in Java – FAQs
Q1. When should I override equals and hashCode in Java?
When engaging with collections, it is advisable to override them.
Q2. What is the significance of the hashCode() and equals() methods?
They are utilized to define object equality and facilitate the effective application of objects in hash-based data structures such as HashMap, HashSet, etc.
Q3. Should I always override equals?
Equals should be overridden if and only if your objects possess a logical identity that is distinct from their physical identity.
Q4. What differentiates == from equals() in Java?
The string.equals() method evaluates the content equality of two strings, whereas the == operator assesses the reference or memory location of objects.
Q5. Can two objects possess the same hashcode yet not be equal?
Two objects can share the same hashcode while remaining NOT necessarily equal.
Q6. What occurs if we do not override the run method?
No code will be executed when a thread is initialized.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.