Comparing Objects in Java

SHARE & COMMENT :

Comparing Objects in Java

In Java comparing two value object is not straight forward. Here we will see how we can compare two value objects in Java.

For that first we will create a value object called “MyValueObject”. This value object contains two properties.

  1. firstName
  2. lastName.

Both the properties are of type string.

also read:

In the same class we also have a overridden method which does the comparison for us. This method “public boolean equals(Object obj)” takes the properties and compare them individually. if the properties values are all equal then it returns true or it will return false. By doing this our test class will just call the equals method on the object to make sure if the objects are equal or not.

package com.blogspot.javawave;

/**
 *
 * @author dhanago
 */
public class MyValueObject
{

    private String firstName;
    private String lastName;

    /**
     * This constructor is used to set the two properties values in the class.
     *
     * @param firstName
     * @param lastName
     */
    public MyValueObject(String firstName,
                          String lastName)
    {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public boolean equals(Object obj)
    {
        boolean isEqual = false;
        if (this.getClass() == obj.getClass())
        {
            MyValueObject myValueObject = (MyValueObject) obj;
            if ((myValueObject.firstName).equals(this.firstName) &&
                    (myValueObject.lastName).equals(this.lastName))
            {
                isEqual = true;
            }
        }

        return isEqual;
    }
}
Test class is given below:

/*
 */
package com.blogspot.javawave;

/**
 *This class is used to test compare the value object.
 *
 * @author dhanago
 */
public class TestCompareValueObject
{

    /**
     * This is the main method used to test compare the value object.
     * @param arg
     */
    public static void main(String[] arg)
    {
        MyValueObject obj1 = new MyValueObject("Muthu", "Kumar");
        MyValueObject obj2 = new MyValueObject("Muthu", "Kumar");

        if (obj1.equals(obj2))
        {
            System.out.println("Both the objects are equal");
        }
        else
        {
            System.out.println("Both the objects are not equal");
        }
    }
}

This one of the way we can easily compare the value objects in Java.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better