Iterator in Java

前端 未结 3 1085
后悔当初
后悔当初 2021-01-21 12:46

What is Iterator and collections? Does these two have any relations?

// the interface definition
Interface Iterator {
    boolean hasNext();
    Object next();          


        
3条回答
  •  旧时难觅i
    2021-01-21 12:59

    An iterator is most commonly used as a mechanism for going through the elements of a collection.

    The concept is not specific to Java at all, though the specific interface definition you show is.

    See the Wikipedia article on Iterator for some discussion of what it means and how it's done in assorted languages including Java.

    In Java, it is an Interface, so you can indeed implement your own, but sensible ones are defined for the collections in Java's collections library and for any Java Collection implementation the method

    collection.iterator()
    

    should return an iterator that will traverse the elements of that collection.

    Also see the javadoc for Collection and Iterator for more.

提交回复
热议问题