hash code method not working? StackOverflowError
So, I do not understand why I cannot define my own public int hashCode() function for my class. I get the error: Exception in thread "main" java.lang.StackOverflowError | when I do. It works when i change it to hashcode()
Here is the code:
Code:
public class LabeledPoint {
private int x;
private int y;
private String label;
public LabeledPoint(int xx, int yy, String aLabel)
{
x = xx;
y = yy;
label = aLabel;
}
/**
* Gives hashcode of object
*/
public int hashCode()
{
return this.hashCode();
}
/**
* Determines if two objects are equal
* @return true if they are,
* false if not
*/
public boolean equals(LabeledPoint lp)
{
if( x == lp.x )
if( y == lp.y )
if( label.equals(lp.label) )
return true;
return false;
}
}
Code:
public class LabeledPointTest {
public static void main(String[] args)
{
LabeledPoint a = new LabeledPoint(1,1, "a");
LabeledPoint b = new LabeledPoint(1,1,"b");
if( a.equals(b))
System.out.println("a == b");
else
System.out.println("a != b");
LabeledPoint c = a;
if( c.equals(a) )
System.out.println("a == c");
else
System.out.println("a != c");
System.out.println("a hash code: "+ a.hashCode() );
System.out.println("b hash code: "+ b.hashCode() );
System.out.println("c hash code: "+ c.hashCode() );
}
}
Re: hash code method not working? StackOverflowError
OK, let's look at your hashCode() method and walk through it pretending we're the JVM (a useful exercise to practice and get good at!):
First, your method:
Code:
public int hashCode()
{
return this.hashCode();
}
Next, let's pretend we're the JVM and that this method gets called, what happens:
Code:
hashCode() gets called
return method calls hashCode again
whose return method calls hashCode again
whose return method calls hashCode again
whose return method calls hashCode again
whose return method calls hashCode again
whose return method calls hashCode again
whose return method calls hashCode again
.... etc...
where will this recursive method calling itself end? The answer -- when the program runs out of stack memory and crashes!
Solution: don't recursively call the method inside of itself.