集合的ListIterator的用法
来源:互联网 发布:linux改文件名 编辑:程序博客网 时间:2024/06/11 13:37
在说ListIterator之前,对于Iterator迭代器都应该很熟悉,在jdk1.2后出现的,代替了Enumeration接口,用于集合的遍历操作。而ListIterator也是迭代器,它的父接口就是Iterator,主要用于List及其子类型。
public interface ListIterator<E> extends Iterator<E>查看源码:
public interface ListIterator<E> extends Iterator<E> { //正向遍历列表时,如果列表迭代器有多个元素,则返回 true boolean hasNext(); //返回列表中的下一个元素 E next(); //返回对next的后续调用所返回元素的索引 int nextIndex(); //如果以逆向遍历列表,列表迭代器有多个元素,则返回 true boolean hasPrevious(); //返回列表中的前一个元素 E previous(); //返回对previous的后续调用所返回元素的索引 int previousIndex(); //从列表中移除由next或previous返回的最后一个元素 void remove(); //用指定元素替换next或previous返回的最后一个元素 void set(E e); //将指定的元素插入列表 void add(E e);}用法示例
public class ListIteratorTest {@Testpublic void test1(){List<String> list = new ArrayList<String>();list.add("one");list.add("two");list.add("three");list.add("four");ListIterator<String> iter = list.listIterator();//正向遍历while(iter.hasNext()){//获取元素的索引int index = iter.nextIndex();String str = iter.next();System.out.println(index+":"+str);}System.out.println("---------------------------");//反向遍历while(iter.hasPrevious()){//获取元素的索引int index = iter.previousIndex();String str = iter.previous();System.out.println(index+":"+str);}}@Testpublic void test2(){List<String> list = new ArrayList<String>();list.add("one");list.add("two");list.add("three");list.add("four");ListIterator<String> iter = list.listIterator();iter.next();System.out.println(list);//[one, two, three, four]//指定元素替换next()返回的值iter.set("AA");System.out.println(list);//[AA, two, three, four]//删除元素"AA"iter.remove();System.out.println(list);//[two, three, four]//添加元素iter.add("BB");System.out.println(list);//[BB, two, three, four]}}
总结:Iterator和ListIterator区别和联系?相同点:都是迭代器,当需要对集合中的元素进行遍历而不需要干预遍历过程时,两种都可以使用不同点:1).使用范围不同,Iterator可以应用于所有集合,Set,List和Map和这些集合的子类型,而ListIterator只能用于List及其子类型2).ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasPrevious()和 previous()方法实现逆向(顺序向前遍历)3).ListIterator可以定位当前索引的位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能4).ListIterator有add方法,可以向List中添加对象,而Iterator不能5).都可以实现删除对象,但是ListIterator可以实现对象的修改,Iterator只能遍历不能修改
阅读全文
0 1
- 集合的ListIterator的用法
- ListIterator listIterator():List集合特有的迭代器
- ListIterator的用法
- java集合中list集合基本用法及List集合特有的迭代器ListIterator
- Iterator和ListIterator的用法
- 列表迭代器ListIterator的用法
- 黑马程序员------集合的遍历Iterator/ListIterator
- List集合特有的迭代器,ListIterator
- List集合的迭代神器ListIterator
- 【集合】Iterator和ListIterator的区别和联系
- java Iterator和ListIterator的区别和用法
- List和ListIterator的常见用法及特性
- ListIterator等的使用。
- ListIterator的双向遍历
- ListIterator用法
- listIterator用法
- 黑马程序员--07.集合框架--03.【列表List集合的共性方法】【列表迭代器ListIterator】
- List集合ListIterator和Iterator迭代器区别与用法
- 安卓(android)之间的传值
- 运动侧边栏广告函数插件
- 《深入理解计算机系统第三版》第三章家庭作业参考答案
- 立个目标
- Binary tree Preorder -iterative methond(stack)
- 集合的ListIterator的用法
- python 1
- Vue.js--基本命令&组件化应用构建
- 千寻(Engram)介绍
- angularjs实战之filter使用一
- 安卓8.0 新功能 新特性
- JavaFX设置Button圆角
- Irrelevant Elements UVA
- python初学1