Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it not possible for looping a class that directly implements Iterator?

My question is: Is it possible to go through a container only by implementing Iterator, i.e. without implementing Iterable?

Is it possible to do this:

//From somewhere
Container c = new Container();
//I add elements to the list in the c object.

for(String s : c){
    //Warning: It is not applicable for this expression...
}


class Container implements Iterator<String>{
    //Here I implement a single linked list

    //Here I implement all of the methods of Iterator
}
like image 606
wagashi Avatar asked Nov 19 '25 18:11

wagashi


1 Answers

Even though this kind of design is nothing but ridiculous, and just to entertain your question, you can write this:

public class Container implements Iterable<String>, Iterator<String> {
  @Override public Iterator<String> iterator() { return this; }

  ... everything else you envision for your class ...
}

Then you'll be able to use

for (String s : container)

You may write this as a learning experience, but I strongly advise you never to try it on a real project. The main reason against it is the expectation on the iterator method to always return a fresh, independent iterator, while this implementation achieves the opposite. To give a specific example, imagine someone needing to iterate over the Cartesian product of your container with itself:

for (String s1 : container)
  for (String s2 : container) 
     processPair(s1, s2);

Every Java programmer will tell you that, beyond any doubt, processPair will be called with each possible pair from the container. The behavior they would instead see from your class would make their heads spin. If a bug in production was ever traced to this implementation, your teammates would... let's just say they wouldn't appreciate it.

like image 51
Marko Topolnik Avatar answered Nov 22 '25 07:11

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!