Set doesn't allow duplicate then why is it allowing ?
Because you are short-circuiting the definition of what a duplicate is. If the 'duplicates' don't have the same hashCode() then they most likely won't end up in the same bucket, and can't be considered equal. Since your code doesn't provide a good hashing function the two 'duplicate' objects will have different hashCode()s. Then, on the off chance they do get into the same bucket, you don't give a good equals() method. Since you don't tell the HashSet how to compare the objects, it relies on Object's implementation: and Object's implementation uses identity ( obj1 == obj2). Since your two objects are not the same exact Object this would be false.
By not providing your own equals() method you are not telling HashSet how to tell if two different objects are 'duplicates.' By not providing the a good hashCode() you are making sure they don't get close enough to even be compared as duplicates.
It is not a default hashCode() but the implementation inherited from Object. That will probably give hash codes which differ even modulo 0x10, so the equals method is never called. You are not fulfilling the general contract for hashCode() that two objects which return true from equals() return the same hash code. You can therefore expect apparently incorrect behaviour from hash‑based collections.
Your implementation with * does fulfil the general contract for hashCode() and your object prints true false when executed.
meeta gaur wrote:I was expecting true and false, because even if i do comment out hashCode(), it will use default hashCode() , so why doesn't equals work here ? why it can't check duplicate here ?
And just to fortify what Campbell said: If you implement equals() and you want your object to work in a hashed Collection or Map, you MUST implement an equivalenthashCode() method; so it stands to reason that if you only comment out one of them, it won't work.
Bats fly at night, 'cause they aren't we. And if we tried, we'd hit a tree -- Ogden Nash (or should've been).
Articles by Winston can be found here
And remember: there is no such thing as a default hash code. Two distinct objects will almost certainly return different hash codes if you use the java.lang.Object#hashCode() implementation.