my dog learned polymorphism*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Problem with hashcode and size Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Problem with hashcode and size" Watch "Problem with hashcode and size" New topic
Author

Problem with hashcode and size

Tommi Vd
Ranch Hand

Joined: Apr 23, 2009
Posts: 49
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

Joined: Apr 20, 2009
Posts: 804
    
    1

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.


SCJP6, SCWCD5, OCE:EJBD6.
BLOG: http://leakfromjavaheap.blogspot.com
shivendra tripathi
Ranch Hand

Joined: Aug 26, 2008
Posts: 263
Override the hashCode() instread of writing your own method hashcode(). If you notice carefully "C" is in capital in original metod.

SCJP 1.5(97%) My Blog
Lucas Smith
Ranch Hand

Joined: Apr 20, 2009
Posts: 804
    
    1

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

Joined: Aug 16, 2005
Posts: 14114
    
  16

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.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9293
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
 
Consider Paul's rocket mass heater.
 
subject: Problem with hashcode and size