将两个实体与 Set inside with java 进行比较
Comparing two entities with Set inside with java
我有里面有 Set 的实体
class A {
public Set<B> b;
}
当我尝试比较两个实体 A 时,我遇到了如何比较集合 b 和集合 b 字段的问题。 hashCode 和 equals 被自动覆盖,但它们没有正确比较。我应该怎么办?如何在不依赖实现的情况下正确比较两组?
通常,当一个集合的元素相等时,这个集合也相等:
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;
所以这一切都取决于 class B 的 equals()。你能给出那个实现吗?
根据 java 文档,equals 方法很好,所以我想知道它有什么问题。
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).
你有具体的例子说明哪里出了问题,即不工作吗?
我有里面有 Set 的实体
class A {
public Set<B> b;
}
当我尝试比较两个实体 A 时,我遇到了如何比较集合 b 和集合 b 字段的问题。 hashCode 和 equals 被自动覆盖,但它们没有正确比较。我应该怎么办?如何在不依赖实现的情况下正确比较两组?
通常,当一个集合的元素相等时,这个集合也相等:
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;
所以这一切都取决于 class B 的 equals()。你能给出那个实现吗?
根据 java 文档,equals 方法很好,所以我想知道它有什么问题。
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).
你有具体的例子说明哪里出了问题,即不工作吗?