wood burning stoves 2.0*
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


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please explain the output" Watch "Please explain the output" New topic
Author

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
Marshal

Joined: Mar 22, 2005
Posts: 42267
    
  64
What output does it produce? What in particular do you not understand about it?


Ping & DNS - my free Android networking tools app
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

Hi,

The output produced was 3.

Sean Clark
Rancher

Joined: Jul 15, 2009
Posts: 377

Hey,

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.

Sean


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.


Regards
Salil Verma

Regards
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: 121

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%
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain the output