4

I have a two sets of LinkedHashSet objects, within this objects I have other objects that have more LinkedHashSet.

My question is:

Does the equals method (default) checks if all the inside HashSets are the same? Or do I have to overwrite it?

Ivan Santos
  • 624
  • 1
  • 8
  • 21

2 Answers2

8

By default it will make sure the contents of the HashSets are equals(). LinkedHashSet is also ordered, but this is not used in hashCode or equals so they could have different orders and still be equals = true.

In short, the order doesn't matter for equals of HashSets, and "equals" is not "same". "same" usually means its the same object.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

The contract for Set.equals() is that every member of each set is contained in the other. Each contains test relies on the equals() method of the objects in the sets.

This specification requires that no Set implementation can rely on the default implementation of equals(), which is object identity. (As far as the Set specification goes, the objects in the set are free to use the default Object.equals() to test equality. But if you have a set of sets, the objects in the (outer) set are themselves Set objects, and thus subject to the same Set contract regarding equals().)

For more info, see the docs for Set.equals() and Set.contains(Object).

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521