Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why can not I use toString().length() as a hashCode() return?

 
Joey Sanchez
Ranch Hand
Posts: 88
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


What am I missing? Is there a recurrent call to hashCode() method because of default toString() method?
 
Paul Clapham
Sheriff
Pie
Posts: 20762
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The stack trace tells you what methods were called to produce that exception. You didn't post it here, or any part of it, so have a look at it and you should be able to see for yourself.

If you can't figure out what the stack trace is telling you, then post it here (or at least part of it, I expect it's very long) and people will explain it to you.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to have a look at the Javadocs for toString in the Object class. That should make it clearer what's happening.
 
Himai Minh
Ranch Hand
Posts: 1229
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no implementation in main method. I don't see any exception when I run the program.
 
Joey Sanchez
Ranch Hand
Posts: 88
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The source code of toString method of Object class, it looks like: -



So, it internally invokes hashCode() method. Now, since you have overrided the hashCode method, it will invoke the hashCode method of your class, which agains invokes toString method of Object class.

This will certainly result in StackOverFlowError

We can rather override the toString method in your class, to make it work.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic