每当我尝试打印 B 类的哈希码时,我都会遇到上述错误,请告诉我我的代码有什么问题?
class B {
@Override
public int hashCode(){
System.out.println(this.hashCode());
//return this.hashCode();
}
}
public class Testing
{
public static void main(String[] args)
{
/*A a = new A(0, null, 1.20);
A a1 = new A(1,null,1.20);
A a3 = null;*/
B b = new B();
System.out.println(b.hashCode());
//System.out.println(a.equals(a1));
//System.out.println(a.equals(a1));
}
}
最佳答案
你正在创建无限递归调用 hashCode
inside hashCode:
class B {
@Override
public int hashCode(){//<----------------------┐
// │ this path is infinite
System.out.println(this.hashCode()); // <----┘
//return this.hashCode();
}
}
为了避免这种情况:
hashCode
。 hashcode
class
没有直接继承,它将始终调用 Object
hashCode 方法。或
自己编码。
注意:要覆盖
并创建一个有效的hashCode
方法,您需要在B
类中至少有一个字段。
@Override
public int hashCode(){
// code it, or better, make your IDE code it for you
}
关于java - 覆盖哈希码方法时获取 "Stack overflow error ",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32733269/