List.equals 为假,尽管列表中的所有对象都相等

List.equals is false despite all objects in list being equal

我有一个对象列表,比方说 Article,这是一个相当复杂的嵌套对象。我将省略实际的 class 因为它真的不重要;了解 Article 已实施 equals()(使用 AutoValue)可能很重要。

我有两个列表:

List<Article> list1 = getSomeArticles(); 
List<Article> list2 = getOtherArticles();

现在我检查它们是否相等:

boolean listsAreEqual = list1.equals(list2); 

这个returnsfalse。 但我检查是否一个。两个列表具有相同的大小和 b。索引 i 处的每个项目在两个列表中都相等:

if (list1.size() != list2.size()) {
  return; 
}

for (int i = 0; i < list1.size(); i++) {
  Article article1 = list1.get(i);
  Article article2 = list2.get(i); 

  if (!article1.equals(article2)) {
    return; 
  }
}

// All items in the two lists are equals, but list2.equals(list2) is false

两个列表似乎包含完全相同的项目,但是 list1.equals(list2) returns false

怎么可能?

他们应该是平等的。您的代码有问题。来自 documentation:

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order. This definition ensures that the equals method works properly across different implementations of the List interface.

当然,除非 List 实现覆盖了 java.util.List 的默认值。