Comparing Objects in Java: equals() vs Objects.equals()
The equals() method in Java is commonly used for comparison, and developers often override it in custom classes to determine object equality. Consider the following example of a User class with an overridden equals method:public class User {
private String username; // User's login name
private int age; // User's age
private String ...
Posted on Tue, 19 May 2026 00:26:22 +0000 by ColinP
Why hashCode Must Be Overridden When equals Is Overridden in Java
Entity Class Definition
Let's define a simple Rectangle class that overrides the equals method to compare objects based on their width and height values instead of reference equality.
class Rectangle {
private int width;
private int height;
public int getWidth() {
return width;
}
public void setWidth(int width) {
...
Posted on Wed, 13 May 2026 13:15:07 +0000 by nolos
Implementing Custom Objects as HashMap Keys in Java
In Java, the HashMap implementation uses the hashCode() method to determine the storage bucket for a key and the equals() method to check for key equality. The default implementation in the Object class generates a hash code based on the object's memory address. This behavior creates a problem when using custom objects as keys: two distinct ins ...
Posted on Sat, 09 May 2026 05:35:46 +0000 by elbowgrease