Javase Getting started learning the iterator of the 38:java set frame

Source: Internet
Author: User

One iterator interface

An iterator is a design pattern that is an object that can traverse and select objects in the sequence, and the developer does not need to know the underlying

Structure. Iterators are often referred to as "lightweight" objects because they are less expensive to create.

The iterator in Java (Iterator) gives us a common way to access the elements in the collection. What you can know is that it just provides a

interface, and does not provide the true iterator class. Iterator is an iterator that iterates over the collection.

The iterator interface defines the following methods:


The iterator functionality in Java is relatively simple and can only be moved one way:

(1) Use method iterator () requires the container to return a iterator object. The first time you call Iterator's next () method, it returns the first element of a sequence

Of

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

(3) Use Hasnext () to check if there are elements in the sequence and return true if there are still elements that can iterate.

(4) use remove () to delete the newly returned element of the iterator. This method is the only security method that removes the element during the iteration.

two iterable interface

Java also provides a iterable interface, the function of the Iterable interface is "return" an iterator, the interface's iterator () method returns a

A standard iterator implementation. Implementing this interface allows the object to be the target of the foreach statement. You can traverse your underlying sequence through the foreach syntax.

The Iterable interface contains a iterator () method capable of producing iterator, and the Iterable interface is used by foreach to move through the sequence. So if

Any class that implements the Iterable interface is created and can be used in a foreach statement.

The only method defined in the Iterable interface:


All collection types that implement the collection interface have a iterator () method that returns an object that implements the iterator interface. Iterator Object

Called an iterator that facilitates the traversal of elements within an object container.

three examples

As mentioned above, there are three methods defined in Java's iterator excuse: Hasnext () returns True;next () if there are still elements to iterate over

Returns the next element of the iteration; remove () removes the last element returned by the iterator from the collection pointed to by the iterator.

We can assume that the iterator iterator is the position between the two elements, and we can use Hasnext () to determine if the current position has a meta-

Of Use the next () method to return the following element, and move the position to the position before the next element. For the Remove () method, we remove the current

The element in front of the position, so we must call the Remove () method at least once before calling the next () method. The position of the iterator described here is

The object of the iteration does not exist, but we are supposed to illustrate this method accurately.

We can iterate through the elements in the Java collection using three loop bodies:

(1) using while loop traversal

Instance:

Import java.util.*;p ublic class test{public static void Main (string[] args) {List List = new ArrayList ();                List.add ("AA");                List.add ("BB");                List.add ("CC");//Use the while loop to iterate through the elements in the collection//Use the collection's iterator () to return a iterator object iterator iter = List.iterator ();//Use Hasnext () method to determine if there is a next element                while (Iter.hasnext ()) {///Use the next () method to return the element String str = (string) iter.next ();                        System.out.println (str);}}}                

Operation Result:


(2) Use for loop traversal

Instance:

Import java.util.*;p ublic class test{public static void Main (string[] args) {List List = new ArrayList ();                List.add ("one");                List.add ("both");                List.add ("three");//Use the For loop to iterate through the elements in the collection for (Iterator iter = List.iterator (); Iter.hasnext ();) {                      string str = (string) Iter.next ();                      System.out.println (str);}}}                

Operation Result:


(3) using the foreach statement to traverse

The so-called foreach statement refers to a new loop structure in JDK 5.0 that can be used to process each element in the collection without having to consider the set

Standard. The foreach statement is fairly straightforward for traversing an array or collection. As you can see, we traverse the set in the course of the previous learning process

The element objects in the closing are all used in this way.

The format is as follows:

for (variable:collection) {           statement;}

Instance:

Import java.util.*;p ublic class test{public static void Main (string[] args) {//defined array int[] arr = {1,2,3,4,5};for (int I:arr ) {System.out.println (i);} System.out.println ("-----------------");//Definition of the collection list L = new ArrayList (); L.add (New String ("AAA")); L.add ("New string" (" BBB ")); L.add (New String (" CCC ")); for (Object o:l) {System.out.println (o);}}}

Operation Result:


Of course, the use of the Foreach Loop structure is also flawed: if iterating through an array would be inconvenient to access the subscript value: If you iterate through the collection then with the use

It is not easy to delete the contents of the collection compared to iterator. In addition to simply traversing and reading out the contents, it is not recommended to use the Foreach loop structure.

Look at the information on the Internet when you read a lot about the use of Java iterators articles, see a very detailed article, the address is a Java iterator

(go) (iterator and the difference between the For loop) , written well. The main thing we learned when we were learning was the Java API. So always check

API, learn to use the API, we write program code will be a higher level.


Javase Getting started learning the iterator of the 38:java set frame

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.