equals() and contains()

Book.java
TestCollections.java

To support Collection's contains() method, we should override Object's equals() method.

Object
+ equals(Object) : boolean
+ hashCode() : int
+ toString() : String
...more, of course
Implementations of the equals() method should have these properties:
  • x.equals(x) should return true (reflexive).
  • x.equals(y) should return true if and only if
    y.equals(x) returns true (symmetric).
  • If x.equals(y) returns true
    and y.equals(z) returns true,
    then x.equals(z) should return true (transitive).
  • x.equals(null) should return false.
The default implementation of equals returns true if and only if x and y refer to the same object (x == y).
public class Book {
    String title;
    int    isbn;

    Book(String title, int isbn) {
        this.title = title;
        this.isbn  = isbn;
    }

    public boolean equals(Object object) {
        if (object == null) {
            return false;
        }
        if (object == this) {
            return true;
        }
        if (object.getClass() == this.getClass()) {
            Book other = (Book) object;
            return this.title.equals(other.title) 
               && (this.isbn == other.isbn);
        }
        return false;
    }
}
import java.util.*;

public class TestCollections {
    public static void main(String[] args) {
        List list = new LinkedList();
        list.add(new Book("Patterns", 12345));
        list.add(new Book("Examples", 23456));

        Book patterns = new Book("Patterns", 12345);

        System.out.println("We have it: " 
                           + list.contains(patterns));
    }

}