转载

Notes about the hashCode & equals

Java

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;
    }
}

本文由Evil Muggle 创作,采用 知识共享署名4.0 国际许可协议进行许可

本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名

最后编辑时间为: Oct 26, 2018 at 07:41 am

原文  https://heiybb.com/hashcode.hf
正文到此结束
Loading...