0

I have entity with Set inside

class A {
public Set<B> b;
}

When I'm trying to compare two entities A I have a problem with how to compare Set b with Set b fields. hashCode and equals are overrided automatically but they didn't compare correctly. What should I do? How to compare correctly two sets without depending on realization?

Bohdan Myslyvchuk
  • 1,657
  • 3
  • 24
  • 39

2 Answers2

2

Usually, when the entries of a set are equal, the set is also equal:

Set<String> a = new HashSet<>(Arrays.asList("a", "b", "c"));
Set<String> b = new HashSet<>(Arrays.asList("c", "b", "a"));

System.out.println(a.equals(b)); //true;

So it will all depend on the equals() of class B. Could you give that implementation?

JensS
  • 1,151
  • 2
  • 13
  • 20
0

According to the java doc the equals method is fine, so I wonder what's wrong with it.

Compares the specified object with this set for equality. Returns true if the given object is also a set, the two sets have the same size, and every member of the given set is contained in this set. This ensures that the equals method works properly across different implementations of the Set interface. This implementation first checks if the specified object is this set; if so it returns true. Then, it checks if the specified object is a set whose size is identical to the size of this set; if not, it returns false. If so, it returns containsAll((Collection) o).

Do you have a concrete example on what is going wrong, i.e. not working?