Iterator迭代器的使用

付费节点推荐


免费节点


节点使用教程


[t]迭代器(Iterator)[/t]

迭代器是一种设计模式,它是一个对象,它可以遍历并选择序列中的对象,而开发人员不需要了解该序列的底层结构。迭代器通常被称为“轻量级”对象,因为创建它的代价小。

public interface Iterable<T>

  Iterator<T> iterator()
Returns an iterator over a set of elements of type T

 Collection接口拓展了接口Iterable,根据以上的对Iterable接口的定义可以发现,其要求实现其的类都提供一个返回迭代器Iterator<T>对象的方法。

迭代器Iterator<T>接口的的定义为:

Interface Iterator<E>
boolean hasNext()
Returns true if the iteration has more elements.

E next()
Returns the next element in the iteration.

void remove()
Removes from the underlying collection the last element returned by the iterator (optional operation).

Java中的Iterator功能比较简单,并且只能单向移动:

(1) 使用方法iterator()要求容器返回一个Iterator。第一次调用Iterator的next()方法时,它返回序列的第一个元素。注意:iterator()方法是java.lang.Iterable接口,被Collection继承。

(2) 使用next()获得序列中的下一个元素。

(3) 使用hasNext()检查序列中是否还有元素。

(4) 使用remove()将迭代器新返回的元素删除。

 Iterator是Java迭代器最简单的实现,为List设计的ListIterator具有更多的功能,它可以从两个方向遍历List,也可以从List中插入和删除元素。

package cn.bcoder;
import java.util.*;
public class Example {

public static void main(String[] args) {
Integer [] a={1,2,3,4,5,6,7,8};
List <Integer>list=new ArrayList(Arrays.asList(a));
Iterator <Integer>it=list.iterator();
while(it.hasNext()){
Integer in=it.next();
System.out.print("\t"+in.intValue());
}

}

}

未经允许不得转载:Bcoder资源网 » Iterator迭代器的使用

相关推荐

更多优质资源关注微信公众号: bcoder

bcoder
赞 (0)
分享到:更多 ()

评论 0

评论前必须登录!

登陆 注册