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

    } 

} 

in this code i'm trying to print hashcode through System.out.println is generating the StackOverflowError. why i'm getting StackOverflowError Thank you

Vasinda
  • 83
  • 6
  • 2
    Here's [something](https://stackoverflow.com/questions/1949454/understanding-basic-recursion) to deep dive more into recursions. – soufrk Jun 08 '18 at 11:09
  • How about you set a breakpoint and debug the program for 1 minute? Or simply take a good look at the stacktrace of the StackOverflowError. – luk2302 Jun 08 '18 at 11:17

3 Answers3

12

In your code this.hashCode() will call itself without any termination condition. That means it goes into recursion without any termination condition. I believe you are trying to use super.hashCode(). Your code should be like :

@Override
public int hashCode() {
    System.out.println("hi this is my hashcode " + super.hashCode());
    return super.hashCode();
}
Amit Bera
  • 7,075
  • 1
  • 19
  • 42
3

You are recurrsively calling the hashcode method, of your objct till the stack overflows. The method keeps calling itself until it can no longer track of how many time it called itself, causing the overflow error. Change to,

 public int hashCode() { 
        return this.value.hashCode();
} 
Antho Christen
  • 1,369
  • 1
  • 10
  • 21
2

In your hashCode method you do: this.hashCode(), causing a recursion that only finishes when the stack is full. So calculate a value and print that value instead.

When you call hashCode(), that call calls hashCode(), and then that call calls hashCode(), etc. etc. etc. until Java runs out of memory (every time you call a method, it takes up a little bit of memory until the method returns).

Venki WAR
  • 1,997
  • 4
  • 25
  • 38