equals() and contains()


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

+ 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 instanceof Book) {
            Book other = (Book) object;
            return this.title.equals(other.title) 
               && (this.isbn == other.isbn);
        } else {
            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));