How would one implement equals in a java-class which implements an interface that extends Iterable?
The interface
public interface MyInterface extends Iterable<String> {
...
}
The concrete class
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) {
How should I check that both this instance and the other instances contains the same set of strings? The easy way would to only check equals against this implementation and not the interface, but that sounds like cheating.
if (otherObject instanceof MyClass) { ... } // easy, just myStrings.equals(...)
but
if (otherObject instanceof MyInterface) { ... } // compare two iterators?
Or am I missing something? I must implement hashCode aswell, and if two objects are equal should not their hashcodes be identical hence equals must only check against MyClass to fullfil this contract?!
}
}
One way would be to use Guava Iterables.elementsEqual method.
http://docs.guava-libraries.googlecode.com/git-history/release09/javadoc/com/google/common/collect/Iterables.html#elementsEqual(java.lang.Iterable, java.lang.Iterable)