I have the following collection of objects:
Set<MyClass> test = new LinkedHashSet<MyClass>();
but MyClass
does not override the hashcode
and equals
methods.
Can have the above collection only unique objects even the MyClass does not override the hashCode
and equals
methods?
The default implementation of equals
is to check identity (i.e., use the ==
operator). Your LinkedHashSet
(or any other HashSet
, for that case) will contain unique objects in the sense you won't be able to add the same object twice. However, if you create two instance exactly the same way (e.g., pass the same arguments to the constructor), your set will still contain both of them, as they are not equals
.