java – 为什么在这个例子中调用hashcode?

前端之家收集整理的这篇文章主要介绍了java – 为什么在这个例子中调用hashcode?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有人可以解释为什么在下面的例子中调用 hashCode
import java.util.List;

public class JSSTest extends Object{

    public static void main(String args[]){

        JSSTest a = new JSSTest();
        JSSTest b = new JSSTest();
        List<JSSTest> list = new java.util.ArrayList<JSSTest>();
        list.add(a);
        list.add(b);
        System.out.println(list.get(0));
        System.out.println(list.get(1));
    }

    @Override
    public boolean equals(Object obj){
        System.out.println("equals");
        return false;
    }

    @Override
    public int hashCode(){
        System.out.println("hashCode");
        return super.hashCode();
    }
}

结果:

hashCode 0
JSSTest@1bab50a
hashCode 0
JSSTest@c3c749

解决方法

默认的toString()实现调用hashCode.这与列表无关.

这是一个相当小的repro:

public class JSSTest {

    public static void main(String args[]){
        JSSTest test = new JSSTest();
        // Just to show it's not part of creation...
        System.out.println("After object creation");
        test.toString();
    }

    @Override
    public boolean equals(Object obj){
        System.out.println("equals");
        return false;
    }

    @Override
    public int hashCode(){
        System.out.println("hashCode");
        return super.hashCode();
    }
}

(您可以覆盖toString()以显示在/ super call / after之后.)

它在Object.toString()中有记录:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance,the at-sign character `@’,and the unsigned hexadecimal representation of the hash code of the object. In other words,this method returns a string equal to the value of:

06001

原文链接:https://www.f2er.com/java/128139.html

猜你在找的Java相关文章