Home > Java > javaTutorial > body text

Detailed tutorial on Iterator

Y2J
Release: 2017-05-12 09:25:32
Original
1489 people have browsed it

Iterator is a pattern that can separate the traversal behavior of sequence type data structures from the traversed objects. Next, I will share with you the Java Iterator through this article_Compiled by Power Node Java Academy, friends in need For reference

Iterator is a pattern that can separate the traversal behavior of a sequence type data structure from the object being traversed, that is, we do not need to care about what the underlying structure of the sequence looks like. As long as you get this object, you can traverse the interior of this object using an iterator.

1.Iterator

Java provides a specialized iterator Object <>Iterator, we can implement this interface for a sequence to provide a standard Java iterator. Iterator interfaceThe implemented function is to "use" an iterator.

Document definition:

Package java.util;
 publicinterface Iterator<E> {
 boolean hasNext();//判断是否存在下一个对象元素
 E next();
 void remove();
 }
 Package java.util;  
 public interface Iterator<E> { 
   boolean hasNext();//判断是否存在下一个对象元素 
   E next(); 
   void remove(); 
 }
Copy after login

2. Iterable

Java also provides an Iterable interface. The function of the Iterable interface after implementation is to "return" an iterator. Our commonly used sub-interfaces that implement this interface are: Collection< E>, Deque, List, Queue, Set, etc. The iterator() method of this interface returns a standard Iterator accomplish. Implementing this interface allows objects to be the target of Foreach statements. You can traverse your underlying sequence through the Foreach syntax.

The Iterable interface contains an iterator() method that can generate an Iterator, and the Iterable interface is used by foreach to move in the sequence. So if you create any class that implements the Iterable interface, you can use it in the foreach statement.

Document definition:

Package java.lang; 
 import java.util.Iterator;
 public interface Iterable<T> {
 Iterator<T> iterator();
 }
Copy after login

Document definition:

 Package java.lang;   
 import java.util.Iterator;  
 public interface Iterable<T> {  
   Iterator<T> iterator();  
 }
Copy after login

Simple example of using Iterator

 import java.util.*; 
 publicclass TestIterator { 
 public static void main(String[] args) {
 List list=new ArrayList(); 
 Map map=new HashMap(); 
 for(int i=0;i<10;i++){ 
 list.add(new String("list"+i) ); 
 map.put(i, new String("map"+i)); 
 } 
 Iterator iterList= list.iterator();//List接口实现了Iterable接口 
 while(iterList.hasNext()){ 
 String strList=(String)iterList.next(); 
 System.out.println(strList.toString()); 
 } 
 Iterator iterMap=map.entrySet().iterator(); 
 while(iterMap.hasNext()){ 
 Map.Entry strMap=(Map.Entry)iterMap.next(); 
 System.out.println(strMap.getValue());
 }
 }
 }
Copy after login

Simple example of using Iterator

import java.util.*;   
 public class TestIterator {   
  public static void main(String[] args) {   
    List list=new ArrayList();   
    Map map=new HashMap();   
    for(int i=0;i<10;i++){   
     list.add(new String("list"+i) );   
      map.put(i, new String("map"+i));   
    }   
    Iterator iterList= list.iterator();//List接口实现了Iterable接口   
     while(iterList.hasNext()){ 
   String strList=(String)iterList.next();   
      System.out.println(strList.toString());   
    }   
   Iterator iterMap=map.entrySet().iterator();   
    while(iterMap.hasNext()){   
     Map.Entry strMap=(Map.Entry)iterMap.next();   
      System.out.println(strMap.getValue()); 
   
    } 
  } 
 }
Copy after login

The interface Iterator will expand its functions according to the situation in different sub-interfaces, such as the iterator ListIterator for List, which can only be used for access to various List classes. ListIterator can move in both directions. Added methods such as previous().

3. Iterator is paired with generics

Iterator works on any one of the collection classes Implementation classes can return such an Iterator object. Can be applied to any class.

Because the types of objects that can be loaded into collection classes (List, Set, etc.) are uncertain. When taken out from the collection, they are all of the Object class type, which takes time. It will be very troublesome to perform forced conversion. Using generics means telling the collection in advance to determine the type of collection to be loaded, so that it can be used directly without displaying Type conversion. It is very convenient.

4. The relationship between foreach and Iterator

for each is a new addition in jdk5.0loopStructure can be used to process each element in the collection without considering the collection subscript.
The format is as follows

for(variable:collection){ statement; }
Copy after login

Define a variable to temporarily store each element in the collection and execute the corresponding statement (block). Collection must be an arrayor a class object that implements the alterable interface.

The above example uses generics and forEach writing:

import java.util.*;
 public class TestIterator {  
 public static void main(String[] args) {
 List<String> list=new ArrayList<String> (); 
 for(int i=0;i<10;i++){ 
 list.add(new String("list"+i) ); 
 } 
 for(String str:list){
 System.out.println(str); 
 }
 }
Copy after login

The above example uses generics and forEach writing:

import java.util.*; 
 public class TestIterator {  
  public static void main(String[] args) {  
    List<String> list=new ArrayList<String> ();   
    for(int i=0;i<10;i++){ 
      list.add(new String("list"+i) ); 
    } 
    for(String str:list){ 
     System.out.println(str); 
    }  
 }
Copy after login

It can be seen that using The advantage of the for each loop statement is that it is more concise and less error-prone. You don't have to worry about the starting and ending values ​​of the subscript. forEach is not a keyword, the keyword is still for, and the statement is implemented by iterator. The biggest difference between them is the remove() method. Generally, the delete and add methods are methods of specific collections, for example:

List list = new ArrayList();
list.add(...); list.remove(...);
Copy after login

但是,如果在循环的过程中调用集合的remove()方法,就会导致循环出错,因为循环过程中list.size()的大小变化了,就导致了错误。 所以,如果想在循环语句中删除集合中的某个元素,就要用迭代器iterator的remove()方法,因为它的remove()方法不仅会删除元素,还会维护一个标志,用来记录目前是不是可删除状态,例如,你不能连续两次调用它的remove()方法,调用之前至少有一次next()方法的调用。forEach就是为了让用iterator循环访问的形式简单,写起来更方便。当然功能不太全,所以但如有删除操作,还是要用它原来的形式。

4 使用for循环与使用迭代器iterator的对比

采用ArrayList对随机访问比较快,而for循环中的get()方法,采用的即是随机访问的方法,因此在ArrayList里,for循环较快

采用LinkedList则是顺序访问比较快,iterator中的next()方法,采用的即是顺序访问的方法,因此在LinkedList里,使用iterator较快。从数据结构角度分析,for循环适合访问顺序结构,可以根据下标快速获取指定元素.而Iterator 适合访问链式结构,因为迭代器是通过next()和Pre()来定位的.可以访问没有顺序的集合.

而使用 Iterator 的好处在于可以使用相同方式去遍历集合中元素,而不用考虑集合类的内部实现(只要它实现了 java.lang.Iterable 接口),如果使用 Iterator 来遍历集合中元素,一旦不再使用 List 转而使用 Set 来组织数据,那遍历元素的代码不用做任何修改,如果使用 for 来遍历,那所有遍历此集合的算法都得做相应调整,因为List有序,Set无序,结构不同,他们的访问算法也不一样.

【相关推荐】

1. Java免费视频教程

2. YMP在线手册

3. JAVA初级入门视频教程

The above is the detailed content of Detailed tutorial on Iterator. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!