Java iterator [go]

Source: Internet
Author: User

An iterator is a pattern that allows the traversal of a data structure of a sequence type to be separated from the object being traversed, that is, we don't have to care what the underlying structure of the sequence looks like. As soon as you get this object, you can iterate through the inside of the object using an iterator.

1.Iterator

Java provides a specialized iterator, <<interface>>iterator, that we can implement for a sequence that interface to provide a standard Java iterator. The iterator interface implements a function that is "using" an iterator.

Document definition:

[Java]View Plaincopyprint?
    1. Package java.util;
    2. Public interface Iterator<e> {
    3. boolean hasnext (); //Determine if the next object element exists
    4. E next ();
    5. void Remove ();
    6. }

2.Iterable

Java also provides a iterable interface, the Iterable interface after the implementation of the function is "return" an iterator, we commonly used to implement the interface has a sub-interface: Collection<e>, Deque<e>, list<e Queue<e>, set<e>, etc. the iterator () method of the interface returns 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. Therefore, if you create any class that implements the Iterable interface, you can use it in a foreach statement.

[Java]View Plaincopyprint?
    1. Document definition:
    2. Package Java.lang;
    3. Import Java.util.Iterator;
    4. Public interface Iterable<t> {
    5. Iterator<t> Iterator ();
    6. }
[Java]View Plaincopyprint?
  1. A simple example of using iterator
  2. Import java.util.*;
  3. Public class Testiterator {
  4. public static void Main (string[] args) {
  5. List list=New ArrayList ();
  6. Map map=New HashMap ();
  7. For (int i=0;i<10;i++) {
  8. List.add (new String ("list" +i));
  9. Map.put (i, new String ("map" +i));
  10. }
  11. Iterator iterlist= list.iterator (); the//list interface implements the Iterable interface
  12. While (Iterlist.hasnext ()) {
  13. String strlist= (String) iterlist.next ();
  14. System.out.println (Strlist.tostring ());
  15. }
  16. Iterator Itermap=map.entryset (). Iterator ();
  17. While (Itermap.hasnext ()) {
  18. Map.entry strmap= (Map.entry) itermap.next ();
  19. System.out.println (Strmap.getvalue ());
  20. }
  21. }
  22. }
  23. <span style="Color:rgb (0, 0, 153); font-size:18px; " > </span><span style="Color:rgb (0, 0, 153); font-size:18px; " ></span>

Interface iterator expands functionality in different sub-interfaces, such as an iterator listiterator for a list, which can only be used for access to a variety of list classes. Listiterator can be moved in both directions. Added methods such as previous () .

3 Iterator and generics collocation

Iterator can return such a iterator object to any one of the implementation classes in the collection class. can be applied to any one class.

Because the types of objects that can be loaded by the collection class (list and set, etc.) are indeterminate, the type of object that is removed from the collection is the type of object, and it is cumbersome to use generics, which is to tell the collection in advance to determine the type of the collection to be loaded. This allows for direct use without the display of type conversions. Very convenient.

The relationship between 4.foreach and iterator

For each is a newly added looping structure that can be used to process each element in the collection without having to consider the set jdk5.0.
The format is as follows
for (variable:collection) {statement;}
Defines a variable that is used to stage each element in the collection and executes the corresponding statement (block). Collection must be an array or a class object that implements the Lterable interface.

[Java]View Plaincopyprint?
  1. The above example uses generics and foreach notation:
  2. Import java.util.*;
  3. Public class Testiterator {
  4. public static void Main (string[] args) {
  5. list<string> list=New arraylist<string> ();
  6. For (int i=0;i<10;i++) {
  7. List.add (new String ("list" +i));
  8. }
  9. For (String str:list) {
  10. System.out.println (str);
  11. }
  12. }

As you can see, the advantage of using the For Each loop statement is that it is more concise, less error-prone, and does not care about the starting and ending values of the subscript.

foreach is not a keyword, a keyword or a for, statements are implemented by iterator, and their biggest difference is in the Remove () method.

General calls to delete and add methods are methods of a specific collection, for example:

List List = new ArrayList (); List.add (...); List.remove (...);

However, if the remove () method of the collection is called during the loop, it causes a loop error because the size of the list.size () changes during the loop, causing an error. So, if you want to delete an element of a collection in a looping statement, use the Remove () method of the iterator iterator, because its remove () method not only removes the element, but also maintains a flag that records whether it is currently a deleted state, for example,   You cannot call its remove () method two times in a row, calling a call to the next () method at least once.

foreach is designed to make it easier to write in the form of a iterator loop. Of course the function is not too full, so but if there is a delete operation, or to use its original form.

4 using the For loop versus using the iterator iterator

There's something in the efficiency.

The use of ArrayList is faster for random access, and the Get () method in the For loop is a random access method, so in ArrayList, the For loop is faster

The use of LinkedList is sequential access is faster, iterator in the next () method, the use of sequential access method, so in LinkedList, using iterator faster

From the data structure point of view, the for loop is suitable for the access order structure, and the specified element can be obtained quickly according to the subscript. Iterator is suitable for accessing chained structures because iterators are positioned by next () and pre (). You can access a collection without order.  

The advantage of using Iterator is that you can iterate over the elements in the collection in the same way, regardless of the internal implementation of the collection class (as long as it implements the Java.lang.Iterable interface), and if you use Iterator to traverse the elements in the collection, once you no longer use List to use Set to organize the data, the code that traverses the elements does not have to make any changes, and if you use the for to traverse, all the algorithms that traverse this set have to be adjusted accordingly, because the list is ordered, the set is unordered, the structure is different, and their access algorithms are not the same.

Original link: http://blog.csdn.net/wanghuan203/article/details/7279742

Java iterator [go]

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.