迭代器iterator与listiterator

Iterator接口是Java Collection Frameword的成员,是对collection进行迭代的迭代器有如下三个方法:

boolean hasnext()    如果仍有元素可以迭代,则返回 true

E next()         返回迭代的元素

void remove()     从迭代器指向的 collection 中移除迭代器返回的最后一个元素(可选操作)。

所谓的迭代器返回的最后一个元素,即就是上一个iterator.next()返回的元素。

而Iterator子接口有ListIterator与XMLEventReader接口,ListIterator系列表迭代器,允许程序员按任一方向遍历列表、迭代期间修改列表,并获得迭代器在列表中的当前位置。ListIterator 没有当前元素;它的光标位置 始终位于调用 previous() 所返回的元素和调用 next() 所返回的元素之间。长度为 n 的列表的迭代器有 n+1 个可能的指针位置。ListIterator主要多了逆向迭代的功能与set功能

ListIterator有如下一些方法

void add(E e)
          将指定的元素插入列表(可选操作)。
 boolean hasNext()
          以正向遍历列表时,如果列表迭代器有多个元素,则返回 true(换句话说,如果 next 返回一个元素而不是抛出异常,则返回 true)。
 boolean hasPrevious()
          如果以逆向遍历列表,列表迭代器有多个元素,则返回 true
 E next()
          返回列表中的下一个元素。
 int nextIndex()
          返回对 next 的后续调用所返回元素的索引。
 E previous()
          返回列表中的前一个元素。
 int previousIndex()
          返回对 previous 的后续调用所返回元素的索引。
 void remove()
          从列表中移除由 nextprevious 返回的最后一个元素(可选操作)。
 void set(E e)
          用指定元素替换 nextprevious 返回的最后一个元素(可选操作)。

下来我们用代码进行演示

package test1;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/*
 * 关于Iterator、ListIterator
 */
public class Demo1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			List<String> list = new ArrayList<>();
			list.add("张三");
			list.add("李四");
			list.add("王五");
			
			
			/*
			 * 第一种迭代方法
			 */
			System.out.print("从前向后迭代依次迭代----->");
			Iterator it = list.iterator();
			while(it.hasNext()){
				System.out.print(it.next()+"   ");
			}
			
			/*
			 * 第二种迭代方法
			 * 从后往前迭代
			 * 注意:list.listIterator()的定位是在第一个元素
			 */
			
			System.out.println("\n-------------------------------------");
			System.out.print("从后向前迭代------>");
			ListIterator<String> it1 = list.listIterator(list.size());
			while(it1.hasPrevious()){
				System.out.print(it1.previous()+"   ");
			}
			
			
			/*
			 * 第三种迭代方法
			 * 顺序改变
			 */
			System.out.println("\n---------------------------------");
			System.out.print("改变迭代顺序-------->");
			ListIterator<String> it2= list.listIterator(2);
			while(it2.hasPrevious()){
				System.out.print(it2.previous()+"    ");
			}
			System.out.print(it2.nextIndex()+":"+it2.next()+"  ");
			System.out.print(it2.nextIndex()+":"+it2.next()+"  ");
	}
}
 
 

以下为运行结果

猜你喜欢

转载自blog.csdn.net/m0_37687058/article/details/79835677