Java-iterator Summary

Source: Internet
Author: User

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&LT;?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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.