为什么this.hashcode()正在生成stackoverflower错误

Vas*_*da -3 java

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()); 

    } 

} 
Run Code Online (Sandbox Code Playgroud)

在这段代码中我试图通过System.out.println打印hashcode生成StackOverflowError.为什么我得到StackOverflowError谢谢

Ami*_*era 12

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

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