next up previous
Next: Note on comparisons: comparison Up: Unit 05 Previous: Note on comparisons: lexicographic

Note on comparisons: equality between objects

As for strings, to test whether two objects of a class are equal, we cannot use ==, because it tests the equality of the references to the two objects. Instead, we have to define a suitable method that takes into account the structure of the objects of the class.

Example:

Referring to the class BankAccount developed in Unit 4, we could add to such a class the definition of a predicate equalTo(), which we can use to compare two bank accounts:

public boolean equalTo(BankAccount ba) {
  return this.name.equals(ba.name) &&
         this.surname.equals(ba.surname) &&
         this.balance == ba.balance;
}

In other words, two bank accounts are considered equal if they coincide in the name and surname of the owner (this is checked using the equals() method for strings) and if they have the same balance (this is checked using ==, since balance is an instance variable of the primitive type float).

Example of usage:

BankAccount ba1 = new BankAccount("Mario", "Rossi");     // balance is 0
BankAccount ba2 = new BankAccount("Carla", "Verdi");     // balance is 0
BankAccount ba3 = new BankAccount("Carla", "Verdi");     // balance is 0
BankAccount ba4 = ba2;

System.out.println("ba1 and ba2 equal?    " + ba1.equalTo(ba2));  // NO
System.out.println("ba2 and ba3 equal?    " + ba2.equalTo(ba3));  // YES
System.out.println("ba2 and ba3 coincide? " + ba2 == ba3);        // NO
System.out.println("ba2 and ba4 equal?    " + ba2.equalTo(ba4));  // YES
System.out.println("ba2 and ba4 coincide? " + ba2 == ba4);        // YES

Note: Actually, there is a standard technique to define an equality predicate that is based on overriding of the method equals() inherited from Object. This technique will be shown in later courses.


next up previous
Next: Note on comparisons: comparison Up: Unit 05 Previous: Note on comparisons: lexicographic