• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with hashcode and size

 
Tommi Vd
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following example out of my book and implemented this in a main class in eclipse:




Now the result in the book is:

- when hashcode method is commented the size is 3
- when hashcode method is uncommented the size is 2

But when i try this in eclipse, it gives me two times the output 3

What's right? Is the book wrong?
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that Eclipse didn't notice the change. You have to rebuild all.
Without overriden hashcode, you use hashcode from Object, which returns always distinct values so every object is considered different - equals is not even invoked.
 
shivendra tripathi
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Override the hashCode() instread of writing your own method hashcode(). If you notice carefully "C" is in capital in original metod.
 
Lucas Smith
Ranch Hand
Posts: 808
1
Android Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah - I have not looked carefully - you did not override hashCode() method - you just defined distinct method which had no common things with hashCode() from Object
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15216
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The @Override annotation exists to help you catch mistakes like writing hashcode() instead of hashCode(). If you would have used it, like this:

then you would have gotten a compiler error, telling you that hashcode() does not override any method in a superclass.

By adding @Override to a method, you tell the compiler that the method is supposed to override a superclass method - and if it doesn't, the compiler will complain.

Annotations are not part of the SCJP exam, but it's useful to know them ofcourse.
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also use == to compare Strings only if you want to check about String pool otherwise use equals method. Your equals method is using == for string comparison...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic