Compare objects in java

If you want to compare if plain old java objects have the same properties, it is easiest to override the equals method.  This way, if you initialise objects on different places, you can be certain when comparing that they are the same.

We will show you how to do it with this simple class:

public class Insect
{
    private int legs;
    private int eyes;
    private int colour;
    private String sortName;
}

Override equals

@Override
public boolean equals(Object o)
{
    if (this == o)
    {
        return true;
    }

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

    final Insect that = (Insect) o;

    if (this.legs != that.legs)
    {
        return false;
    }

    if (this.eyes != that.eyes)
    {
        return false;
    }

    if (this.colour != that.colour)
    {
        return false;
    }

    if (this.sortName != null ? (this.sortName != that.sortName) : (that.sortName != null))
    {
        return false;
    }

    return true;
}

Override hashCode()

@Override
public int hashCode()
{
    int hash = super.hashCode();
    hash = 14 * hash + this.legs;
    hash = 14 * hash + this.eyes;
    hash = 14 * hash + this.colour;
    hash = 14 * hash + (this.sortName != null ? this.sortName.hashCode() : 0);
    return hash;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.