Iterator in Java

前端 未结 3 1080
后悔当初
后悔当初 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-21 13:09

    Technically iterators and collections are not directly related. However Iterators are mostly used together with collections to interate over the objects contained in the collection.

    Iterators are a general and flexible concept that allows to interate objects without depending on the exact implementation of the entity that they iterate over.

    0 讨论(0)
  • 2021-01-21 13:18

    The Java collections are, as the name says, collections of things. If you don't know that word, look it up in a dictionary.

    There are many types of collections. Take for example the mathematical concept of a set. You can put arbitrary things in a set, but it will never contain the same thing more than once. The things in the set are not ordered, that is you cannot say A comes before B. Another type of collection is a list. A list can contain the same thing more than once, and the order of the things in the list is important.

    What all these collections have in common is that they contain things, which in Java are called elements. When you want to know which things are in a certain collection, you iterate over the collection, which is just another term for going through all elements. This is what an Iterator does. It basically starts at the beginning of a collection, you can always ask whether there is a next element (hasNext()), and if there is, you can get access to that element (next()), until you have iterated over all elements in the collection.

    0 讨论(0)
提交回复
热议问题