Adobe Interview Question
SDE1sCountry: United States
Interview Type: In-Person
mostly agree. however, equals is not override, so I think s1.equals(s2) is false since the default equals is used which is only true when both are the same object.
when added to hashset, they are duplicated since their hashcode is the same (they share the same string literal).
The above behavior shows inconsistency since only hashCode while not equals overriden
The consequence would be s2 is not added since it has the same hashcode as s1 thus treated as duplicated even though they are not "equal"
s1.equals(s2) will return true. String class has overriden equals method and therefore s1 ans s2 will not use Object class equals method. whearas equals is not overriden in HashTest that's the reason h1.equals(h2) will return false as it is using Object class return method.
Ans is 3. Since h1 and h2 have same hashcode, they will both go to the same bucket as since equals method is not overridden in HashTest class. If along with hashcode(), equals method would have been overridden, only h1 will go in bucket and h2 will not go in bucket.
Since string overrides both equals and hashcode, so only s1 will go in bucket.
Answer is 3.
- varunnitk.jain May 30, 2013HashSet will not keep duplicate so it will take one out of s1 and s2. Also it will take both h1 and h2
How HashSet work is
It will use hashcode to find memory to store.
It will use equals method to find duplicate. s1.equals(s2) is true
but h1.equals(h2) if false.
that's the reason that it isrecommended to override equals and hashcode both.