Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.
@gnat i might have pasted a wrong link, i can't remember. anyway, this question is actually much more similar to 2 questions posted on StackOverflow - see the links in my answer. but since SO is technically another site, the input form wouldn't let me submit a link to neither of them
@overexchange correct, but Serializable does nothing, it's a marker interface. Iterable is more like Parcelable in that you're actually supposed to flesh some implementation out. You can delegate iteration to a child class (eg. a collection you enwrap) just by returning its iterator as your own. And if Java ever got reified generics (like C#), MyClass could simultaneously support Iterable<Integer> and Iterable<String>, and you could iterate it as an integer or string sequence alike. Thanks for accepting my answer
@overexchange ok I see - but if you only had Iterator as an inner class, how would the outer world know that it can iterate over MyClass in a for ... in loop? Making it Iterable says that explicitly and it seems like the cleanest possible way
@overexchange and you wouldn't want your MyClass to be its own iterator, for the reasons explained above - but if Iterable and Iterator were combined in one interface, you could not avoid it.
@overexchange you don't want your iterable MyClass instance to know that it's being iterated by someone right now, and to keep track of it - to know that this someone is on the 5th element at the moment ;) For one, because it would make difficult for someone else to iterate over its elements at the same time. As for squashing Iterable and Iterator into one interface, it would violate Single Responsibility Principle. Being an iterator (keeping track of the act of iterating over elements), and being able to build new iterators are two different responsibilities.
@CarlManaster why not, but this, in my opinion, doesn't do anything - it's rainmaking, with all due respect. But whatever soothes your soul ;) I'm not here for arguments
I use them once in a while, but it feels kinda hackish - the downsides, off top of my head, are that you can't help the fact they're inherited, so once you mark a class with one, all its children get marked as well whether you want it or not. And they seem to encourage bad practice of using instanceof instead of polymorphism
I imagine the OP is aware of them, but they're actually a bit controversial. While some authors recommend them (eg. Josh Bloch in "Effective Java"), some claim they're an antipattern and legacy from times when Java had no annotations yet. (Annotations in Java are roughly the equivalent of attributes in .NET). My impression is that they're much more popular in Java world than .NET.