Check for equality of two iterators?

How can I check equality of two iterators using JUnit?

Is there a built-in method or is it just by comparing each item in it?

Thanks, Sriram


source to share

3 answers

There is no sane way to check if Iterator

s is
equal .

If it's crazy in this case, you might want to delve into the implementation of the particular type of iterator you are testing and use reflection to access private stuff and compare this (I am sure with enough code source analysis that you would find what should be held for two ListIterators, for example).

Or if this is your own iterator type, then export some variables to help you and use them instead of reflection.

Iterating through and comparing elements is only a weak guarantee, as you can iterate over a clone of your collection, that is, iterators look the same but are not.

Just don't do it.



You cannot (and should not) check for equality of iterators, only those from the base sets. To do this, you can iterate over both and compare each pair of elements in turn, you guessed it. Note that this efficiently consumes at least one of the iterators. And the result depends on the state of the iterators at the beginning of the test, so this method is brittle. Therefore, it is best to get the underlying collections and check them directly for equality (using their method equals

) whenever possible.

Why would you ever try to check for equality of two iterators? If you explain your specific problem, we may be able to suggest a better alternative.



There is no "classical" concept of equality for Iterator

, except for object identity, because they are mutable in the "worst" way.

In a JUnit script, it would be preferable to collect the values next()

returned in a list, eg. using Guava ImmutableList.copyOf(Iterator<T>)

and then go to assertThat(a, is(b))

as described in this SO answer



All Articles