予而不语

Notes about the hashCode & equals

import java.util.HashSet;
import java.util.Set;

public class HashEqualTest {
    public static void main(String[] args) {
        Set<Foo> fooSet = new HashSet<>();
        
        Foo f1 = new Foo(1);
        Foo f2 = new Foo(1);
        Foo f3 = new Foo(1);
        Foo f4 = new Foo(1);

        fooSet.add(f1);
        fooSet.add(f2);
        fooSet.add(f3);
        fooSet.add(f4);

        System.out.println(fooSet.size());
        System.out.println("Break Point");
        // only the first one element will be stored
    }
}

/**
 * result
 *
 * the add method will check the hashCode first
 * when the hashCode is the same the the equals method will be call
 * to compare the two instance
 *
 * if the hashCode is not override then the hashCode compare return false
 * the equals will no be called
 *
 * override the equals method is strongly not recommended
 * in order to avoid some unpredictable issues
 *
 *
 * when override the equals method, parameter 'Object' type required 
 * not the specific type
 */


class Foo {
    private int f;

    Foo(Integer x) {
        this.f = x;
    }

    public int getF() {
        return f;
    }

    @Override
    public int hashCode() {
        return 17;
    }

    @Override
    public boolean equals(Object obj) {
        return true;
    }

    public boolean equals(Foo obj) {
        return false;
    }
}