Explain the usage of iterator iterators in Java _java

Source: Internet
Author: User

Iterator (iterator)

An iterator is a design pattern that is an object that traverses and selects objects in a sequence, and developers do not need to understand the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because the cost of creating them is small.

The iterator function in Java is simpler and can only be moved in one Direction:

(1) using the method iterator () requires the container to return a iterator. The first time the iterator next () method is invoked, it returns the first element of the sequence. Note: The iterator () method is a java.lang.Iterable interface, inherited by collection.

(2) Use Next () to get the next element in the sequence.

(3) Use Hasnext () to check if there are any elements in the sequence.

(4) Remove the newly returned elements of the iterator using remove ().

Iterator is the simplest implementation of the Java iterator, with more functionality for the list design listiterator, which can traverse the list in two directions or insert and delete elements from the list.

Iterator Applications:

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 for While loop
iterator iter = L.iterator ();
while (Iter.hasnext ()) {
String str = (String) iter.next ();
System.out.println (str);
*/

The above is a small series to introduce the Java iterator iterator usage, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.