java iterator

An iterator is a pattern that enables the traversal of a sequence-type data structure to be decoupled from the object being traversed , i.e. we don't need to care what the underlying structure of the sequence looks like. As long as you get this object, you can use the iterator to traverse the interior of this object.

1.Iterator

Java provides a special iterator «interface»Iterator, we can implement this interface for a sequence to provide standard Java iterators. The function after the Iterator interface is implemented is to "use" an iterator.

Document Definition:

1  Package java.util;  
 2  public  interface Iterator<E> { 
 3    boolean hasNext(); // Determine whether there is the next object element 
4    E next(); 
 5    void remove();
 6 }

 

2.Iterable

Java also provides an Iterable interface. The function of the Iterable interface is to "return" an iterator. The sub-interfaces that we commonly implement this interface are: Collection, Deque, List, Queue, Set  , etc. The iterator of this interface The () method returns a standard Iterator implementation. Implementing this interface allows an object to be the target of a For each statement. You can traverse your underlying sequence with the For each syntax.

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

文档定义:
1 Package java.lang; 
2 
3 import java.util.Iterator;
4 public  interface Iterable<T> { 
5 Iterator<T> iterator();  
6 } 
 
使用Iterator的简单例子
copy code
 1 import java.util.*;
 2 
 3 public class TestIterator { 
 4 
 5 public  static void main(String[] args) {
 6 
 7    List list=new ArrayList();
 8 
 9    Map map=new HashMap();
10  //初始化list和map的数据
11   for(int i=0;i<10;i++){
12 
13     list.add(new String("list"+i) );
14 
15     map.put(i, new String("map"+i));
16 
17   } 
18 
19 Iterator iterList= list.iterator();//List接口实现了Iterable接口
20   //循环list 
21  while(iterList.hasNext()){
22 
23    String strList=(String)iterList.next();  
24 
25    System.out.println(strList.toString());  
26 
27   } 
28 
29  Iterator iterMap=map.entrySet().iterator();
30   //循环map
31    while(iterMap.hasNext()){
32 
33      Map.Entry strMap=(Map.Entry)iterMap.next();
34 
35      System.out.println(strMap.getValue());  
36 
37    } 
38 
39 } 
40 
41 } 
copy code

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

 

3 Iterator with generics

Iterator can return such an Iterator object to any implementation class in the collection class. Can be applied to any class.

Because the types of objects that can be loaded by collection classes (List and Set, etc.) are uncertain, they are all of Object type when they are taken out of the collection, and they need to be coerced when used, which will be very troublesome. Using generics is to advance Tells the collection to determine the type of the collection to be loaded, so it can be used directly without explicit type conversion. Very handy.

 

4. Relationship between foreach and Iterator

for each is a newly added loop structure in jdk5.0, which can be used to process each element in the collection without considering the subscript of the collection.

The format is as follows

1 for(variable:collection){ statement; }

 

Define a variable to temporarily hold each element in the collection and execute the corresponding statement (block). collection must be an array or a class object that implements the lterable interface.

上面的例子使用泛型和forEach的写法:  
copy code
 1 import java.util.*;
 2 public  class TestIterator { 
 3 
 4 public  static void main(String[] args) {
 5 
 6 List<String> list=new ArrayList<String> ();
 7 
 8 for(int i=0;i<10;i++){
 9   list.add(new String("list"+i) );
10 } 
11 
12 for(String str:list){
13   System.out.println(str); 
14 } 
15 
16 } 
copy code

 

使用for循环时,在循环内使用list.remove()会导致错误,可以使用如下方法:

for(int i = 0; i < list.size();i++){
  if(true){
	list.remove(list.get(i));
	--i;//remove的同时下标跟着减
	}
}

可以看出,使用for each循环语句的优势在于更加简洁,更不容易出错,不必关心下标的起始值和终止值。

forEach不是关键字,关键字还是for,语句是由iterator实现的,他们最大的不同之处就在于remove()方法上。

一般调用删除和添加方法都是具体集合的方法,例如:

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

但是,如果在循环的过程中调用集合的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()来定位的.可以访问没有顺序的集合.

The advantage of using Iterator is that you can traverse 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). If you use Iterator to traverse the elements in the collection, once you no longer use it If List uses Set to organize data, the code for traversing elements does not need to be modified. If for is used to traverse, all algorithms for traversing this set must be adjusted accordingly, because List is ordered, Set is unordered, and the structure is different. Their access algorithms are also different.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326481669&siteId=291194637
Recommended