当前位置:K88软件开发文章中心编程语言JavaJava01 → 文章内容

Iterator迭代器的使用

减小字体 增大字体 作者:佚名  来源:网上搜集  发布时间:2019-1-4 7:53:32

-->

[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中插入和删除元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package cn.k88;
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());
}

}

}

Iterator迭代器的使用