gpt4 book ai didi

java - 覆盖哈希码方法时获取 "Stack overflow error "

转载 作者:行者123 更新时间:2023-12-05 09:21:25 25 4
gpt4 key购买 nike

每当我尝试打印 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();
}
}

为了避免这种情况:

  1. 不要在自身内部调用hashCode
  2. 调用父类(super class)hashcode
    注意:如果在这种情况下,class 没有直接继承,它将始终调用 Object hashCode 方法。

  1. 自己编码。
    注意:覆盖并创建一个有效的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com