//Written by K@stackoverflow
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari", 28));
        people.add(new Person("K", 28));
        people.add(new Person("StackOverflow", 4));
        people.add(new Person("Subash Adhikari", 28));

        for (int i = 0; i < people.size() - 1; i++) {
            for (int y = i + 1; y <= people.size() - 1; y++) {
                boolean check = people.get(i).equals(people.get(y));

                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                System.out.println(check);
            }
        }
    }
}

//written by K@stackoverflow
public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (this.age != other.age) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output:

run:

-- Subash Adhikari - VS - K false

-- Subash Adhikari - VS - StackOverflow false

-- Subash Adhikari - VS - Subash Adhikari true

-- K - VS - StackOverflow false

-- K - VS - Subash Adhikari false

-- StackOverflow - VS - Subash Adhikari false

-- BUILD SUCCESSFUL (total time: 0 seconds)

Answer from Kim on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › overriding-equals-method-in-java
Overriding equals method in Java - GeeksforGeeks
July 23, 2025 - Try it on GfG Practice · Output: Equal · As a side note, when we override equals(), it is recommended to also override the hashCode() method. If we don't do so, equal objects may get different hash-values; and hash based collections, including ...
🌐
Test-king
test-king.com › blog › common-pitfalls-and-best-practices-for-overriding-equals-and-hashcode-in-java
overriding equals and hashCode best practices
Ensure consistency with equals(): If you override equals(), make sure that the objects that are considered equal by the equals() method also return the same hash code. Failing to do so can lead to unexpected behavior in hash-based collections, such as failing to find objects or treating logically ...
🌐
Blogger
javarevisited.blogspot.com › 2011 › 02 › how-to-write-equals-method-in-java.html
Overriding equals() and hashCode() method in Java and Hibernate
Consistently using @Override annotation is also a best practice in Java. 2) Second mistake I have seen while overriding equals() method is not doing null check for member variables which ultimately results in NullPointerException in Java during ...
Top answer
1 of 11
164
//Written by K@stackoverflow
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Person> people = new ArrayList<Person>();
        people.add(new Person("Subash Adhikari", 28));
        people.add(new Person("K", 28));
        people.add(new Person("StackOverflow", 4));
        people.add(new Person("Subash Adhikari", 28));

        for (int i = 0; i < people.size() - 1; i++) {
            for (int y = i + 1; y <= people.size() - 1; y++) {
                boolean check = people.get(i).equals(people.get(y));

                System.out.println("-- " + people.get(i).getName() + " - VS - " + people.get(y).getName());
                System.out.println(check);
            }
        }
    }
}

//written by K@stackoverflow
public class Person {
    private String name;
    private int age;

    public Person(String name, int age){
        this.name = name;
        this.age = age;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }

        if (obj.getClass() != this.getClass()) {
            return false;
        }

        final Person other = (Person) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }

        if (this.age != other.age) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 53 * hash + this.age;
        return hash;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Output:

run:

-- Subash Adhikari - VS - K false

-- Subash Adhikari - VS - StackOverflow false

-- Subash Adhikari - VS - Subash Adhikari true

-- K - VS - StackOverflow false

-- K - VS - Subash Adhikari false

-- StackOverflow - VS - Subash Adhikari false

-- BUILD SUCCESSFUL (total time: 0 seconds)

2 of 11
29

Overloading vs Overriding

Introducing a new method signature that changes the parameter types is called overloading:

public boolean equals(People other){

Here People is different than Object.

When a method signature remains the identical to that of its superclass, it is called overriding and the @Override annotation helps distinguish the two at compile-time:

@Override
public boolean equals(Object other){

Without seeing the actual declaration of age, it is difficult to say why the error appears.

🌐
GeeksforGeeks
geeksforgeeks.org › java › override-equalsobject-hashcode-method
Why to Override equals(Object) and hashCode() method ? - GeeksforGeeks
December 22, 2025 - Example: This program shows why overriding both equals() and hashCode() is necessary when using objects as HashMap keys. ... import java.util.*; class Geek { String name; int id; Geek(String name, int id) { this.name = name; this.id = id; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Geek geek = (Geek) obj; return name.equals(geek.name) && id == geek.id; } @Override public int hashCode() { return id; } } class GFG { public static void main(String[] args) { Geek g1 = new Geek("Ram", 1); Geek g2 = new Geek("Ram", 1); Map<Geek, String> map = new HashMap<>(); map.put(g1, "CSE"); map.put(g2, "IT"); for (Geek geek : map.keySet()) { System.out.println(map.get(geek)); } } }
🌐
Baeldung
baeldung.com › home › java › core java › java equals() and hashcode() contracts
Java equals() and hashCode() Contracts | Baeldung
January 8, 2024 - The default implementation of equals() in the Object class compares the identity of the object. In our example, the income and expenses instances of the Money class have two different identities. Therefore, comparing them with the .equals() method returns false. To change this behavior we must override this method.
🌐
Reddit
reddit.com › r/learnjava › override equals() when comparing objects - why is java designed this way?
r/learnjava on Reddit: Override equals() When Comparing Objects - Why is Java Designed This Way?
January 20, 2023 -

So, as a beginner, I found that comparing objects with the default equals() method actually does almost exactly the same thing like comparing them with ==. In other words, if two variables reference the same object, == will resolve as true and also equals() will resolve as true. But if we have two variables referencing two objects with a different identity but semantically the same (like, hmmm they look same to me! Same variables, etc.!) we actually have to come with our own equals() method and override the Java default method. (And when doing that, why not also override HashCode(), you know).

Now my question is not the typical "why???"(technicaly why it is needed?) but "why???" (why on earth was Java language designed this way)? Why Java does not have e.g. objectsEquals() method that would work for objects comparing all the fields etc. by default?

Why it even has equals() method that works the same as operator ==? In such a universe we could also have methods isTheSame(), isCompletelyTheSame() and thisIsEqual() all doing the same stuff? And also why we are even overriding it? Is it like "Java authors designed this method poorly or too generally, so let us made our better method that does also this and that". Why not create a framework class or our own class or just completely new method like sameObjects() and just use it with our own new beatiful name? Why overriding? Sorry, I am pretending rant, but I am just trying to be a little funny and also as a beginner I do not really understand this equals() override. What I am really trying to say is, I like to understand things deeply, in this case not only, it works basically in this and that way why but why it even exists as a part of our world:-)

Top answer
1 of 7
8

should we always override the equals and hashCode even if we don’t intent at that point to use the class with any Collection classes?

No and I would go even further as to say you probably don't need to override them even if you are going to put them into a collection. The default implementations are perfectly compatible with collections as is. For lists, it's irrelevant anyway.

You should override equals if and only if your objects have a logical identity that is independent of their physical identity. In other words, if you want to have multiple objects that represent the same entity. Integer, is a good example of this. The integer 2 is always 2 regardless of whether there are 100 instances or 1 of the Integer object with the value of 2.

You must override hashcode if you've overridden equals.

That's it. There are no other good reasons to modify these.

As a side note, the use of equals to implement algorithms is highly overused. I would only do this if your object has a true logical identity. In most cases, whether two objects represent the same thing is highly context dependent and it's easier and better to use a property of the object explicitly and leave equals alone. There are many pitfalls to overriding equals, especially if you are using inheritance.

An example:

Let's say you have an online store and you are writing a component that fulfills orders. You decide to override the equals() method of the Order object to be based on the order number. As far as you know, that's the it's identity representation. You query a DB every so often and create objects from the response. You take each Order object and keep it as a key in a set which is all the orders in process. But there's a problem, orders can be modified in a certain time frame. You now might get a response from the DB that contains the same Order number but with different properties.

You can't just write this object to your set because you'll lose track of what was in process. You might end up processing the same order twice. So, what are the options? You could update the equals() method to include a version number or something additional. But now you have to go through your code to figure out where you need to base the logic on the having the same order number and where you need it to be based on the new object identity. In other words, there's not just one answer to whether two objects represent the same thing. In some contexts it's the order, and in some contexts it's the order and the version.

Instead of the set, you should build a map and use the order number as the key. Now you can check for the existence of the key in the map and retrieve the other object for comparison. This is much more straightforward and easy to understand than trying to make sense of when the equals method works they way you need it to for different needs.

A good example of this kind of complexity can be found in the BigDecimal class. You might think that BigDecimal("2.0") and BigDecimal("2.00") are equal. But they are not.

Conclusion:

It can make sense to implement equals() (make sure you update hashcode() too if you do) and doing so doesn't prevent the use of any of the techniques I describe here.

But if you are doing this:

  • Make sure your object is immutable
  • Use every meaningful property of the object to define equals.
  • If you are using inheritance, either:
    1. make equals final on the base class OR
    2. you must check that the actual type matches in subclasses

If any of these aren't followed, you are in for trouble.

2 of 7
4

In Java, if you don’t override anything, equality is defined as object references being equal, and the hash code is the bit pattern of the reference. That works just fine to put objects into containers.

And there are objects where this is exactly right. For example an object representing a window in the UI. Two windows are equal if and only if they are the same window.

PS. It makes absolutely sense to have a set of windows, or a dictionary with windows as keys, or an array of windows and lookup if the array contains some window - so you need to be able to compare windows for equality.

Find elsewhere
🌐
UCSC
users.soe.ucsc.edu › ~eaugusti › archive › 102-winter16 › misc › howToOverrideEquals.html
How and Why to Override the equals Method in Java
For the Object class's equals method ... of Java classes that can be written - clearly an impossible task! So, Object's equals method does the best it can without trying too hard - strict reference equality. IMPORTANT: So, if you want a class that you write to be able to perform logical equality you must override the equals ...
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › MET08-J.+Preserve+the+equality+contract+when+overriding+the+equals()+method
MET08-J. Preserve the equality contract when overriding the equals() method - SEI CERT Oracle Coding Standard for Java - Confluence
That is, when comparing two subclass objects for equality, sometimes their respective fields must also be equal, and other times they need not be equal. Depending on the concept of equality for the subclass, the subclass might override equals(). Furthermore, this method must follow the general contract for equals(), as specified by The Java Language Specification (JLS) [JLS 2015].
🌐
Hostman
hostman.com › tutorials › overriding the equals() method in java
Java: Overriding the equals() Method
December 26, 2025 - Calling a method multiple times should return the same result as long as the object's properties in your implementation do not change. There are also some restrictions in Java on overriding equals().
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
Quora
quora.com › Is-it-a-good-practice-to-override-equals-and-hashCode-in-Java
Is it a good practice to override equals and hashCode in Java? - Quora
Answer (1 of 4): Whenever you override ... have to be equal however. It is good practice though to have as less equal objects as possible to have the same hash code....
🌐
PriorityQueue
nkamphoa.com › home › how to override the equals method properly in java
How to Override the equals Method Properly in Java
September 15, 2025 - Use the @Override annotation: This ensures you are actually overriding a superclass method. Check for reference equality: If both references point to the same object, return true.
🌐
JavaGoal
javagoal.com › home › equals() method in java
equals() method in java & Best practices for Overriding - JavaGoal
July 18, 2022 - As you already know every class in java is the child of the Object class. It means each class inherits the equals() method from the Object class. You can override the equals() method as per your functionality. Suppose you want to compare the object’s own equality condition.
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Implementing equals
It uses a new method canEqual, which defines, for the subclasses, what types should be considered as part of the equals method. ... import java.math.BigDecimal; public class Star { public Star(String name, BigDecimal radius){ this.name = name; this.radius = radius; } public final String getName(){return name;} public final BigDecimal getRadius() {return radius;} @Override public boolean equals(Object aThat){ if (this == aThat) return true; if ( !(aThat instanceof Star) ) return false; Star that = (Star)aThat; return that.canEqual(this) && EqualsUtil.areEqual(this.name, that.name) && EqualsUtil
🌐
Mkyong
mkyong.com › home › java › java – how to override equals and hashcode
Java - How to override equals and hashCode - Mkyong.com
March 24, 2016 - For JDK 7 and above, you can use the new Objects class to generate the equals and hash code values. ... import java.util.Objects; public class User { private String name; private int age; private String passport; //getters and setters, constructor @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof User)) { return false; } User user = (User) o; return age == user.age && Objects.equals(name, user.name) && Objects.equals(passport, user.passport); } @Override public int hashCode() { return Objects.hash(name, age, passport); } }
🌐
Crunchify
crunchify.com › java j2ee tutorials › java collections – hashcode() and equals() – how to override equals() and hashcode() method in java?
Java Collections - hashCode() and equals() - How to Override equals() and hashcode() Method in Java? • Crunchify
December 31, 2021 - For the Best practice use below steps to implement your equals() method: Use this == that to check reference equality · Use instanceof to test for correct argument type · Cast the argument to the correct type · Compare significant fields ...