• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Liutauras Vilda
  • Knute Snortum
  • Bear Bibeault
Sheriffs:
  • Devaka Cooray
  • Jeanne Boyarsky
  • Junilu Lacar
Saloon Keepers:
  • Ron McLeod
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
  • salvin francis
Bartenders:
  • Tim Holloway
  • Piet Souris
  • Frits Walraven

hashSet

 
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Code snippet 1:




In the code snippet 1 :why we do not get the size as 2.I feel the size should be 2 because the hashcode method has not been overidden so some unique hashcodes are created by JVM.So both the elements should get added.please correct me if i am wrong?
 
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are using set of String Object. String of course has override hashCode(), equals() method. So when you are trying to add a string, its equals () method is called and this avoid to be added duplicate String.
So your 2nd String has not been added. so size is 1.
 
gunjan khanuja
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but if the hashcode generated is unique,though the value of string is same..,wont it be added?
 
author
Posts: 23868
141
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

gunjan khanuja wrote:but if the hashcode generated is unique,though the value of string is same..,wont it be added?



As already mentioned, the String class overrides equals/hashCode for string objects to be equals when the string values are equals -- and the hashCode() method conforms to the contract, so two equals strings will have the same hashcode.

Henry
 
A day job? In an office? My worst nightmare! Comfort me tiny ad!
Java file APIs (DOC, XLS, PDF, and many more)
https://products.aspose.com/total/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!