How to compare two objects in java example

You have to correctly override method equals() from class Object

Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.

Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.

For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().

But now, we come to another problem. Let's imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.

There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider "meaningfully equal" to be added to your "no duplicates allowed" set.

Some of the collections that use hashCode()

  • HashSet
  • LinkedHashSet
  • HashMap

Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily

  • EqualsBuilder
  • HashCodeBuilder

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

This post will discuss how to compare two objects in Java.

You should never use the == operator for comparing two objects, since the == operator performs a reference comparison and it simply checks if the two objects refer to the same instance or not. The recommended option to compare two objects is using the equals() method. However, simply calling the equals() method won’t work as expected, as shown below:

    public TV(String company, String model, int warranty) {

        this.warranty = warranty;

    public static void main(String[] args) {

        TV tv1 = new TV("Vu", "Vu Premium 4K TV", 2);

        TV tv2 = new TV("Vu", "Vu Premium 4K TV", 2);

        System.out.println(tv1.equals(tv2));            // false

Download  Run Code

 
The above program will call the equals() method of the Object class, which behaves similar to the == operator as it is not overridden by a class. Therefore, every class should override the equals (and hashCode) method of the Object class and specify the equivalence relation on objects, such that it evaluates the comparison of values in the object irrespective of whether two objects refer to the same instance or not. See this post for more details.

Here’s a simple program that demonstrates the working of the equals() method.

import java.util.Objects;

    public TV(String company, String model, int warranty) {

        this.warranty = warranty;

    public boolean equals(Object o) {

        if (this == o) return true;

        if (o == null || getClass() != o.getClass()) return false;

        return warranty == tv.warranty &&

                Objects.equals(company, tv.company) &&

                Objects.equals(model, tv.model);

        return Objects.hash(company, model, warranty);

    public static void main(String[] args) {

        TV tv1 = new TV("Vu", "Vu Premium 4K TV", 2);

        TV tv2 = new TV("Vu", "Vu Premium 4K TV", 2);

        System.out.println(tv1.equals(tv2));            // true

Download  Run Code

 
You must also override the hashCode() method, since equal objects must have equal hash codes. If you prefer not to override the equals() and hashCode() method, you can create a custom function to check for equality. This is demonstrated below:

import java.util.Objects;

    public TV(String company, String model, int warranty) {

        this.warranty = warranty;

    public static boolean isEqual(TV tv1, TV tv2) {

        if (tv2 == null || tv1.getClass() != tv2.getClass()) {

        return tv1.warranty == tv2.warranty &&

                Objects.equals(tv1.company, tv2.company) &&

                Objects.equals(tv1.model, tv2.model);

    public static void main(String[] args) {

        TV tv1 = new TV("Vu", "Vu Premium 4K TV", 2);

        TV tv2 = new TV("Vu", "Vu Premium 4K TV", 2);

        System.out.println(isEqual(tv1, tv2));            // true

Download  Run Code

That’s all about comparing two objects in Java.


Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding 🙂


Postingan terbaru

LIHAT SEMUA