Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain the output

 
indra negi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please explain the output that will be produced by the following code snippet:
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What output does it produce? What in particular do you not understand about it?
 
Harsh Pensi
Ranch Hand
Posts: 67
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
indra negi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Hi,

The output produced was 3.

 
Sean Clark
Rancher
Posts: 377
Android Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Salil Vverma
Ranch Hand
Posts: 257
Hibernate Oracle Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
indra negi
Ranch Hand
Posts: 68
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Great . Got it.

Thanks to all.
 
Sidharth Khattri
Ranch Hand
Posts: 125
Java Linux Scala
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the hashCode() override method, return again invokes hashCode() on this.str:
public int hashCode() {
return this.str.hashCode();
}

What will this return?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic