Comparing Objects

Contact Us or call 1-877-932-8228
Comparing Objects

Comparing Objects

The operators == and != test if two references point to exactly the same object in memory; they test that the numeric values of the two references are the same.

The equals(Object o) method compares the contents of two objects to see if they are the same (you can override this method for your classes to perform any test you want).

When comparing two objects, the == operator compares the references and not the values of the objects. Similarly, != tests to see if the references point to two different objects (even if they happen to have the same internal values).

The Object class defines an equals(Object) method intended to compare the contents of the objects. The code written in the Object class simply compares the references using ==. This method is overridden for most API classes to do an appropriate comparison. For example, with String objects, the method compares the actual characters up to the end of the string. For classes you create, you would override this method to do whatever comparisons you deem appropriate.

Code Sample:

Java-Control/Demos/Rectangle.java
public class Rectangle {
  private int height;
  private int width;
  
  public Rectangle(int height, int width) {
    this.height = height;
    this.width = width;
  }
  
  public int getArea() {
    return height * width;
  }
  
  public boolean equals(Object other) {
    if (other instanceof Rectangle) {
      Rectangle otherRect = (Rectangle) other;
      return this.height == otherRect.height && 
             this.width == otherRect.width;
    }
    else return false;
  }
}

The equals method compares another object to this object.

This example is necessarily somewhat complicated. It involves a few concepts we haven't covered yet, including inheritance. Because the equals method inherited from Object, it takes a parameter which is an Object, we need to keep that that type for the parameter (technically, we don't need to do it by the rules of Java inheritance, but because other tools in the API are coded to pass an Object to this method). But, that means that someone could call this method and pass in something else, like a String.

So, the first thing we need to do is test that the parameter was actually a Rectangle. If so, we can work with it; if not, there is no way it could be equal, so we return false.

We will cover instanceof later, but, for now, we can assume it does what it implies: test that the object we received was an instance of Rectangle. Even after that test, in order to treat it as a Rectangle, we need to do a typecast to explicitly store it into a Rectangle variable (and again, we will cover object typecasting later). Once we have it in a Rectangle variable, we can check its height and width fields.

In yet another complication, if we write an equals method, we should really write a public int hashcode() method as well, since their meanings are interrelated; two elements that compare as equal should produce the same hashcode.

As an aside, note that private data in one instance of a class is visible to other instances of the same class; it is only otherclasses that cannot see the private elements.

Code Sample:

Java-Control/Demos/ObjectEquivalenceIdentity.java
class ObjectEquivalenceIdentity {
  
  public static void main(String[] args) {
    Rectangle r1 = new Rectangle(10, 20);
    Rectangle r2 = new Rectangle(10, 20);
    if (r1 == r2)
      System.out.println("Same object");
    else
      System.out.println("Different objects");
    if (r1.equals(r2))
      System.out.println("Equal");
    else
      System.out.println("Not equal"); 
  }
}

Since all the important work is done in Rectangle, all we need to do here is instantiate two and compare them using both == and the equals method to see the differing results.

The output should be:

Different objects 
Equal

Testing Strings for Equivalence

Example - write a brief program which has a word stored as a string of text. Print a message asking for a word, read it, then test if they are the same or not.

  • you can preset the message assuming that they are incorrect, then change it if they are correct

Code Sample:

Java-Control/Demos/StringEquals.java
import util.KeyboardReader;

public class StringEquals {
  public static void main(String[] args) {
    String s = "Hello";
    String t = KeyboardReader.getPromptedString("Enter a string: ");
    String message = "That is incorrect";
    if (s.equals(t)) message = "That is correct";
    System.out.println(message);
  }
}
  • try this, then change equals(t) to equalsIgnoreCase(t)
Next