Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please explain the output 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 "Please explain the output" Watch "Please explain the output" New topic

Please explain the output

indra negi
Ranch Hand

Joined: Aug 12, 2009
Posts: 68
Please explain the output that will be produced by the following code snippet:
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
What output does it produce? What in particular do you not understand about it?
Harsh Pensi
Ranch Hand

Joined: Aug 05, 2009
Posts: 67
I think your doubt is why h1.equals(h2) is false.
Its because it is returning h1.str.equals(h2) and not h1.str.equals(h2.str).

SCJP6 - 93% SCWCD5 - 97%
indra negi
Ranch Hand

Joined: Aug 12, 2009
Posts: 68


The output produced was 3.

Sean Clark

Joined: Jul 15, 2009
Posts: 377


As harsh explained you have no implements your equals method correctly, so when it tests to see if the object is in the set then it get false because h1 doesn't equal h2.
Your s1 and s2 do equal therefore only 1 of them will be added.
So you end up with 3 elements in your set.


I love this place!
Salil Vverma
Ranch Hand

Joined: Sep 06, 2009
Posts: 255

Hey Indra,
There would be three objects in the set h1,h2 and s1. h1 and h2 would not be equal reason being in the equals function it performs equals operation of string with HashTest object. In this comparision, it would always return false as they are different instance.
If you want h1 to be logically equal with h2 if they have the same string then you shall have to tweak the code a bit. You can see the example as mentioned below.It would give two objects in the set.

Salil Verma

Salil Verma
indra negi
Ranch Hand

Joined: Aug 12, 2009
Posts: 68

Great . Got it.

Thanks to all.
Sidharth Khattri
Ranch Hand

Joined: Sep 16, 2013
Posts: 125

In the hashCode() override method, return again invokes hashCode() on this.str:
public int hashCode() {
return this.str.hashCode();

What will this return?

OCPJP 6 - 96%
Currently working on Scala at Knoldus Software
I agree. Here's the link:
subject: Please explain the output
It's not a secret anymore!