Home  >  Article  >  Java  >  Summary of Java's Iterator interface

Summary of Java's Iterator interface

黄舟
黄舟Original
2017-03-15 11:55:301453browse

What you see on paper is shallow, but you know you have to do it in detail --Lu You Ask the canal how clear it is to have a source of living water --Zhu Xi


##Iteration The generator is a design A pattern , which is an object that can traverse and select objects in a sequence without the developer needing to know the underlying structure of the sequence. Iterators are often called "lightweight" objects because they are cheap to create.

Terator will be implemented in Collection collection, so you can get an iterator object through iterator()

function, and then you can use the provided The function performs corresponding output operations.

(1) The iterator() method is Java.

lang.Iterator interface, which is implemented by Collection. Use the iterator() method to ask the container to return an iterator.

(2) When the Iterator's

next() method is called for the first time, it returns the first element of the sequence, and will Get the next element in the sequence.

#(3) Use hasNext() to check whether there are any elements in the sequence.

(4) Use remove() to remove

the element newly returned by the iterator.


##Source code of the Iterator interface in Java8:

public interface Iterator<E>
{
    boolean hasNext();//判断是否下一个
    E next();//获取下一个
    default void remove() //删除
    {
        throw new UnsupportedOperationException("remove");
    }
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

Simple example:

list l = new ArrayList();
l.add("aa");
l.add("bb");
l.add("cc");
//方法一
for (Iterator iter = l.iterator(); iter.hasNext();)
 {
     String str = (String)iter.next();
    System.out.println(str);
}
//方法二
Iterator iter2 = l.iterator();
 while(iter2.hasNext())
 {
    String str = (String) iter2.next();
    System.out.println(str);
}

The above is the detailed content of Summary of Java's Iterator interface. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn