繁体   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