File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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: 808

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

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: 808

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: 15092

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 8 API documentation
Ankit Garg

Joined: Aug 03, 2008
Posts: 9465

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
I agree. Here's the link:
subject: Problem with hashcode and size
It's not a secret anymore!