What is the Iterable interface used for?

前端 未结 5 1157
执念已碎
执念已碎 2020-12-08 10:01

I am a beginner and I cannot understand the real effect of the Iterable interface.

5条回答
  •  攒了一身酷
    2020-12-08 10:26

    Besides what Jeremy said, its main benefit is that it has its own bit of syntactic sugar: the enhanced for-loop. If you have, say, an Iterable, you can do:

    for (String str : myIterable) {
        ...
    }
    

    Nice and easy, isn't it? All the dirty work of creating the Iterator, checking if it hasNext(), and calling str = getNext() is handled behind the scenes by the compiler.

    And since most collections either implement Iterable or have a view that returns one (such as Map's keySet() or values()), this makes working with collections much easier.

    The Iterable Javadoc gives a full list of classes that implement Iterable.

提交回复
热议问题