An iterator is a kind of cursor that can be moved around the elements of any set of elements. Thus, its internal state is mainly a pointer to the current element. If you try to find out if it contains a βspecific itemβ, you will have to move the cursor and therefore change the internal state. Changing a state simply by asking a question is definitely bad.
This is even a problem with the mentioned Guava. It will modify the iterator object, just calling the contains method.
Iterable, on the other hand, is just an interface telling the compiler that there is something to iterate over. In most cases, the iterable object will be the collection itself. If you add methods such as "contains" to the Iterable interface, you get a (simplified) version of the Collection interface that already exists. Therefore, there is no need for this.
If you are stuck in your code in some place where you have a link to iterability, but you need collection functionality, you should consider reorganizing your code. Either you should use the collection of interfaces consistently, or ask yourself why you better not use the collection methods at the moment. Thus, your problem is most likely the result of suboptimal code.
On the other hand, I would find it strange to use Iterable as a type for parameters or variables anyway. Technically you can do this, but I think it is intended to be used only in loops.
Wolf s
source share