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?
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.
posted 7 years ago
but if the hashcode generated is unique,though the value of string is same..,wont it be added?
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.