【问题标题】:why this.hashcode() is generating stackoverflowerror为什么 this.hashcode() 会产生 stackoverflowerror
【发布时间】:2018-06-08 19:15:57
【问题描述】:
public class Employee { 
    int id; 
    String value; 
    @Override 
    public boolean equals(Object obj) { 
        return true;   } 
    @Override 
    public int hashCode() { 
        System.out.println("hi this is my hashcode " + this.hashCode()); 
        return this.hashCode();} 
} 
public class TestCH { 
    public static void main(String args[]) 
    { 
        Employee emp1= new Employee(); 
        Employee emp2= new Employee(); 
        Employee emp3= new Employee(); 
        Employee emp4= new Employee(); 

        Map map= new HashMap(); 
        map.put( emp1,1); 
        map.put(emp2,2); 
        map.put(emp3,3); 
        System.out.println("with map "+map.size()); 

    } 

} 

在这段代码中,我试图通过 System.out.println 打印哈希码正在生成 StackOverflowError。为什么我收到 StackOverflowError 谢谢你

【问题讨论】:

  • 这里是something 以深入了解递归。
  • 你设置断点调试程序1分钟怎么样?或者简单地看一下 StackOverflowError 的堆栈跟踪。

标签: java


【解决方案1】:

在您的代码中,this.hashCode() 将调用 itself 而没有任何终止条件。这意味着它在没有任何termination 条件的情况下进入recursion。我相信您正在尝试使用super.hashCode()。你的代码应该是这样的:

@Override
public int hashCode() {
    System.out.println("hi this is my hashcode " + super.hashCode());
    return super.hashCode();
}

【讨论】:

    【解决方案2】:

    您正在递归调用您的对象的hashcode 方法,直到堆栈溢出。该方法一直在调用自己,直到无法再跟踪自己调用了多少次,从而导致溢出错误。 改成,

     public int hashCode() { 
            return this.value.hashCode();
    } 
    

    【讨论】:

      【解决方案3】:

      在您的 hashCode 方法中,您执行以下操作:this.hashCode(),导致递归仅在堆栈已满时完成。所以计算一个值并打印该值。

      当您调用 hashCode() 时,该调用调用 hashCode(),然后该调用调用 hashCode() 等等等等,直到 Java 内存不足(每次调用方法时,它都会占用在方法返回之前有一点内存)。

      【讨论】:

        猜你喜欢
        • 2012-08-08
        • 1970-01-01
        • 2020-02-24
        • 1970-01-01
        • 2015-12-02
        • 2020-08-05
        • 2021-08-10
        • 2017-08-08
        • 2011-01-16
        相关资源
        最近更新 更多