1

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?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
aurelianr
  • 538
  • 2
  • 12
  • 35
  • 6
    It will contain unique objects according to identity, but not according to whatever other definition of equality you have. If you want the collection to contain unique objects according to some non-identity definition of equality, override those methods. – Andy Turner Sep 05 '15 at 15:11
  • [You could resort to commons collections and implement an external hash and equality provider](http://stackoverflow.com/a/20030782/521799) – Lukas Eder Sep 05 '15 at 15:49

1 Answers1

6

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.

Mureinik
  • 297,002
  • 52
  • 306
  • 350