Java Record -58-iterator iterator

Source: Internet
Author: User

Iterator iterators

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.

public interface iterator<e>

An iterator that iterates over the collection. Iterators replace the enumeration in the Java collections Framework. Iterators are two points different from enumerations:

    • Iterators allow callers to take advantage of well-defined semantics to remove elements from the collection that iterators point to during iterations.

    • The method name has been improved.

The methods that are included:

Boolean Hasnext () returns True if there are still elements that can iterate.

E Next () returns the next element of the iteration.

void Remove () removes the last element returned by the iterator from the collection that the iterator points to (optional action).

Use the iteration function:

Before you access a class set through an iterative function, you must get an iterative function. Each collection class provides a iterator () function that returns an iterative function on the class set header. With this iterative function object, you can access each element in the class set, one element at a time. You typically use an iterative function to loop through the contents of a class set, in the following steps:

1. The iterative function of the class set header is obtained by invoking the iterator () method of the class set;

2. Create a loop that calls the Hasnext () method, and iterate as long as Hasnext () returns True.

Inside the loop, each element is obtained by invoking the next () method.


Iterators are typically applied to a while loop:

Iterator iter = Hashset.iterator ();            while (Iter.hasnext ()) {Object obj = Iter.next ();        System.out.println (obj); }


Java Record -58-iterator iterator

Related Article

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.