Paper on the end of the light, I know this matter to preach-Lu He asked the canal that is clear, for Fountainhead-Zhu Xi
An iterator is a design pattern that is an object that can traverse and select objects in a sequence, and the developer does not need to know the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because they are less expensive to create . Terator is implemented in the collection collection, so a iterator object can be obtained through the iterator () function, which can then be output using the provided function. (1) iterator () is the Java.lang.Iterator interface, which is implemented by collection. Using method iterator () requires the container to return a iterator. (2) when the next () method of iterator is called for the first time, it returns the first element of the sequence, followed by the next element in the sequence. (3) use Hasnext () to check if there are elements in the sequence. (4) use remove () to delete the newly returned element of the iterator.
Java8 The source of the iterator interface:
Public Interfaceiterator<E>
{
BooleanHasnext();//determine if the next
ENext();//get the next
default voidRemove()//Delete
{
throw NewUnsupportedoperationexception ("Remove");
}
default voidforeachremaining(CONSUMER<?SuperE> Action) {
Objects.requirenonnull (Action);
while(Hasnext ())
Action.accept (Next ());
}
}
Simple example:
List L =NewArrayList ();
L.add ("AA");
L.add ("BB");
L.add ("CC");
//Method One
for(Iterator iter = L.iterator (); Iter.hasnext ();)
{
String str = (string) iter.next ();
System.out.println (str);
}
//Method Two
Iterator iter2 = L.iterator ();
while(Iter2.hasnext ())
{
String str = (string) iter2.next ();
System.out.println (str);
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java-iterator Summary