簡體   English   中英

是否等於Java類中的實現,該類實現了擴展Iterable的接口?

[英]Equals implementation in a java-class which implements an interface that extends Iterable?

在實現擴展Iterable接口的java類中,一個實現如何實現等價?

介面

public interface MyInterface extends Iterable<String> {
...
}

具體課

public class MyClass implements MyInterface {

  private Set<String> myStrings = new HashSet<String>();

  @Override
  public Iterator<String> iterator() {
    return myStrings.iterator();
  }

  @Override
  public boolean equals(Object otherObject) {

如何檢查該實例和其他實例是否包含相同的字符串集? 簡單的方法是僅檢查此實現是否相等,而不檢查接口是否相等,但這聽起來像作弊。

    if (otherObject instanceof MyClass) { ... } // easy, just myStrings.equals(...)

    if (otherObject instanceof MyInterface) { ... } // compare two iterators?

還是我錯過了什么? 我還必須實現hashCode,如果兩個對象相等,則它們的哈希碼不應該相同,因此,equals必須僅對MyClass進行檢查才能完成此合同?

  }

}

一種方法是使用Guava Iterables.elementsEqual方法。

http://docs.guava-libraries.googlecode.com/git-history/release09/javadoc/com/google/common/collect/Iterables.html#elementsEqual(java.lang.Iterable,java.lang.Iterable)

/**
 * Returns true if all elements in <code>searchFor</code> exist in
 * <code>searchIn</code>, otherwise returns false.
 * 
 * @param searchIn
 *            the collection in which to search for each element in
 *            <code>searchFor</code>
 * @param searchFor
 *            the collection of element to search for
 */
public static boolean containsAll(@Nonnull Iterable<?> searchIn, @Nonnull Iterable<?> searchFor) {
    for (Object o : searchFor) {
        if (!Iterables.contains(searchIn, o)) {
            return false;
        }
    }
    return true;
}

/**
 * Returns true if all elements in <code>searchFor</code> exist in
 * <code>searchIn</code> and no other elements exist in
 * <code>searchIn</code>, otherwise returns false.
 * 
 * @param searchIn
 *            the collection in which to search for each element in
 *            <code>searchFor</code>
 * @param searchFor
 *            the collection of element to search for
 */
public static boolean containsAllAndOnly(@Nonnull Iterable<?> searchIn,
        @Nonnull Iterable<?> searchFor) {
    if (Iterables.size(searchIn) != Iterables.size(searchFor)) {
        return false;
    }

    return containsAll(searchIn, searchFor);
}

比較Set時,即使Collection(其超級接口)包含相同的對象,也永遠不會相等。

如果兩個類相等,則它們必須具有相同的hashCode()。 值得注意的是,HashSet沒有排序,並且具有相同元素的兩個集合可以處於不同的順序。

因此,如果只有一個Iterator,則無論如何都要進行比較之前,必須將所有元素添加到Set中。

作為實驗,我生成了一些您可以使用相同Set獲得的組合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM