java的iterator接口_java Iterator接口和LIstIterator接口分析_java_脚本之家

java  Iterator接口和LIstIterator接口分析

目录

1.Iterator接口

2.ListIterator

3.Iterator和ListIterator的区别

正文

在继续看ArrayList源码之前,先了解Iterator接口和ListIterator接口,下篇文章详细讲解ArrayList是如何实现它们的。

我们知道,接口只是一种规范,当继承接口并实现其中的方法时,要遵循接口对方法的说明。

1.Iterator接口

Iterator接口取代了Java集合框架中的Enumeratrion。Iterators不同于enumerations的地方主要有两点:

Iterators允许调用者在迭代过程中从集合里移除元素;

方法名得到了改善。

Iterator源码如下:

/**

* An iterator over a collection. {@code Iterator} takes the place of

* {@link Enumeration} in the Java Collections Framework. Iterators

* differ from enumerations in two ways:

* Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.

* Method names have been improved.

* This interface is a member of the Java Collections Framework.

* @param the type of elements returned by this iterator*/

public interface Iterator {

/**

* Returns {@code true} if the iteration has more elements.

* (In other words, returns {@code true} if {@link #next} would

* return an element rather than throwing an exception.)

* @return {@code true} if the iteration has more elements

*/

boolean hasNext();

/**

* Returns the next element in the iteration.

* @return the next element in the iteration

* @throws NoSuchElementException if the iteration has no more elements

*/

E next();

/**

* Removes from the underlying collection the last element returned

* by this iterator (optional operation). This method can be called

* only once per call to {@link #next}. The behavior of an iterator

* is unspecified if the underlying collection is modified while the

* iteration is in progress in any way other than by calling this

* method.

*

* @implSpec

* The default implementation throws an instance of

* {@link UnsupportedOperationException} and performs no other action.

*

* @throws UnsupportedOperationException if the {@code remove}

* operation is not supported by this iterator

*

* @throws IllegalStateException if the {@code next} method has not

* yet been called, or the {@code remove} method has already

* been called after the last call to the {@code next}

* method

*/

default void remove() {

throw new UnsupportedOperationException("remove");

}

/**

* Performs the given action for each remaining element until all elements

* have been processed or the action throws an exception. Actions are

* performed in the order of iteration, if that order is specified.

* Exceptions thrown by the action are relayed to the caller.

*

* @implSpec

*

The default implementation behaves as if:

*

{@code

* while (hasNext())

* action.accept(next());

* }

*

* @param action The action to be performed for each element

* @throws NullPointerException if the specified action is null

* @since 1.8

*/

default void forEachRemaining(Consumer super E> action) {

Objects.requireNonNull(action);

while (hasNext())

action.accept(next());

}

}

Iterator接口定义了四个方法以及各个方法的功能,如果有类实现了这个接口,且实现了这些方法,这方法需要实现定义的功能,遵循这些规则:

1).hasNext() 判断容器是否有下一个元素,有则返回true;

2).next() 返回容器中的下一个元素;

3).remove() 移除当前迭代器返回的最后一个元素。这个方法在每次调用next()方法之后只能调用一次;

4).Java 8 增加forEachRemaining方法,它可以实现对余下的所有元素执行指定的操作。

更详细的说明请阅读源码中的注释。

2.ListIterator

ListIterator在Iterator基础上提供了add、set、previous等对列表的操作。但是ListIterator跟Iterator一样,仍是在原列表上进行操作。

ListIterator源码如下:

/**

* An iterator for lists that allows the programmer

* to traverse the list in either direction, modify

* the list during iteration, and obtain the iterator's

* current position in the list. A {@code ListIterator}

* has no current element; its cursor position always

* lies between the element that would be returned by a call

* to {@code previous()} and the element that would be

* returned by a call to {@code next()}.

* An iterator for a list of length {@code n} has {@code n+1} possible

* cursor positions, as illustrated by the carets ({@code ^}) below:

*

* Element(0) Element(1) Element(2) ... Element(n-1)

* cursor positions: ^ ^ ^ ^ ^

*

* Note that the {@link #remove} and {@link #set(Object)} methods are

* not defined in terms of the cursor position; they are defined to

* operate on the last element returned by a call to {@link #next} or

* {@link #previous()}.

*

* This interface is a member of the Java Collections Framework.*/

public interface ListIterator extends Iterator {

// Query Operations

/**

* Returns {@code true} if this list iterator has more elements when

* traversing the list in the forward direction. (In other words,

* returns {@code true} if {@link #next} would return an element rather

* than throwing an exception.)

*

* @return {@code true} if the list iterator has more elements when

* traversing the list in the forward direction

*/

boolean hasNext();

/**

* Returns the next element in the list and advances the cursor position.

* This method may be called repeatedly to iterate through the list,

* or intermixed with calls to {@link #previous} to go back and forth.

* (Note that alternating calls to {@code next} and {@code previous}

* will return the same element repeatedly.)

*

* @return the next element in the list

* @throws NoSuchElementException if the iteration has no next element

*/

E next();

/**

* Returns {@code true} if this list iterator has more elements when

* traversing the list in the reverse direction. (In other words,

* returns {@code true} if {@link #previous} would return an element

* rather than throwing an exception.)

*

* @return {@code true} if the list iterator has more elements when

* traversing the list in the reverse direction

*/

boolean hasPrevious();

/**

* Returns the previous element in the list and moves the cursor

* position backwards. This method may be called repeatedly to

* iterate through the list backwards, or intermixed with calls to

* {@link #next} to go back and forth. (Note that alternating calls

* to {@code next} and {@code previous} will return the same

* element repeatedly.)

*

* @return the previous element in the list

* @throws NoSuchElementException if the iteration has no previous

* element

*/

E previous();

/**

* Returns the index of the element that would be returned by a

* subsequent call to {@link #next}. (Returns list size if the list

* iterator is at the end of the list.)

*

* @return the index of the element that would be returned by a

* subsequent call to {@code next}, or list size if the list

* iterator is at the end of the list

*/

int nextIndex();

/**

* Returns the index of the element that would be returned by a

* subsequent call to {@link #previous}. (Returns -1 if the list

* iterator is at the beginning of the list.)

*

* @return the index of the element that would be returned by a

* subsequent call to {@code previous}, or -1 if the list

* iterator is at the beginning of the list

*/

int previousIndex();

// Modification Operations

/**

* Removes from the list the last element that was returned by {@link

* #next} or {@link #previous} (optional operation). This call can

* only be made once per call to {@code next} or {@code previous}.

* It can be made only if {@link #add} has not been

* called after the last call to {@code next} or {@code previous}.

*

* @throws UnsupportedOperationException if the {@code remove}

* operation is not supported by this list iterator

* @throws IllegalStateException if neither {@code next} nor

* {@code previous} have been called, or {@code remove} or

* {@code add} have been called after the last call to

* {@code next} or {@code previous}

*/

void remove();

/**

* Replaces the last element returned by {@link #next} or

* {@link #previous} with the specified element (optional operation).

* This call can be made only if neither {@link #remove} nor {@link

* #add} have been called after the last call to {@code next} or

* {@code previous}.

*

* @param e the element with which to replace the last element returned by

* {@code next} or {@code previous}

* @throws UnsupportedOperationException if the {@code set} operation

* is not supported by this list iterator

* @throws ClassCastException if the class of the specified element

* prevents it from being added to this list

* @throws IllegalArgumentException if some aspect of the specified

* element prevents it from being added to this list

* @throws IllegalStateException if neither {@code next} nor

* {@code previous} have been called, or {@code remove} or

* {@code add} have been called after the last call to

* {@code next} or {@code previous}

*/

void set(E e);

/**

* Inserts the specified element into the list (optional operation).

* The element is inserted immediately before the element that

* would be returned by {@link #next}, if any, and after the element

* that would be returned by {@link #previous}, if any. (If the

* list contains no elements, the new element becomes the sole element

* on the list.) The new element is inserted before the implicit

* cursor: a subsequent call to {@code next} would be unaffected, and a

* subsequent call to {@code previous} would return the new element.

* (This call increases by one the value that would be returned by a

* call to {@code nextIndex} or {@code previousIndex}.)

*

* @param e the element to insert

* @throws UnsupportedOperationException if the {@code add} method is

* not supported by this list iterator

* @throws ClassCastException if the class of the specified element

* prevents it from being added to this list

* @throws IllegalArgumentException if some aspect of this element

* prevents it from being added to this list

*/

void add(E e);

}

ListIterator的功能更加强大,定义的方法有:

1).hasNext() 向前遍历时,如果有下一个元素返回真;

2).next() 返回下一个元素的值,并将指针加1;

3).hasPrevious() 向相反方向遍历时,如果还有元素返回真;

4).previous() 返回上一个元素的值,并将指针前移1;

5).nextIndex() 返回此时调用next()方法时返回的元素的索引;

6).previousIndex() 返回此时调用previous()方法时返回的元素的索引;

7).remove() 移除最近一次调用next()或previous()方法返回的元素(可选);

8).set(E e) 用元素e将如果此时调用next()或previous()方法返回的元素替换掉;

9).add(E e) 添加元素到此时调用next()返回的元素之前,或此时调用previous()返回的元素之后。

更详细的说明请阅读源码中的注释。

3.Iterator和ListIterator的区别

Iterator和ListIterator的方法对比如下表:

Iterator

ListIterator

hasNext()

hasNext()

覆盖

next()

next()

覆盖

remove()

remove()

覆盖

forEachRemaining(Consumer super E> action)

forEachRemaining(Consumer super E> action)

继承

hasPrevious()

previous()

nextIndex()

previousIndex()

set(E e)

add(E e)

二者的不同之处主要有:

1).Iterator只能单向移动,ListIterator可以双向移动;

2).ListIterator可以删除、替换或添加元素,而Iterator只能删除元素;

3).ListIterator可以返回当前(调用next()或previous()返回的)元素的索引,而Iterator不能。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393301.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

leetcode468. 验证IP地址

编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。 IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1; 同时,IPv4 地…

播客#45:迪伦·以色列

On todays episode, I interview Dylan Israel. Dylan is a software engineer, a YouTuber, and the creator of several programming courses.在今天的一集中,我采访了迪伦以色列。 迪伦(Dylan)是一位软件工程师,一名YouTuber,并且是几门编…

PHPstorm快捷键

当前文件搜索类:ctrln 全文检索文件:ctrlshiftn 收起侧边栏:alt1(自定义) 个人学习记录,持续更新中。。。 转载于:https://www.cnblogs.com/zaijiang/p/7806260.html

JS基础_强制类型转换-Number

https://www.cnblogs.com/ZHOUVIP/p/7225267.html转载于:https://www.cnblogs.com/robinunix/p/11011188.html

JavaScript变量和作用域

JavaScript有两种变量,全局变量和局部变量 如果在任何函数定义之外声明了一个变量,则该变量是全局变量,且该变量的值在整个持续范围内都可以访问和修改 如果在函数定义内声明来了一个变量,则该变量为局部变量。每次执行该函数时都…

python 微信bot_使用Python创建Twitter Bot

python 微信botHave you ever wantd to create a Twitter bot? In this tutorial John G. Fisher shows how to create a bot with Python that tweets images or status updates at a set interval.您是否曾经想创建一个Twitter机器人? 在本教程中,约翰…

leetcode1487. 保证文件名唯一

给你一个长度为 n 的字符串数组 names 。你将会在文件系统中创建 n 个文件夹:在第 i 分钟,新建名为 names[i] 的文件夹。 由于两个文件 不能 共享相同的文件名,因此如果新建文件夹使用的文件名已经被占用,系统会以 (k) 的形式为新…

提高redis cluster集群的安全性,增加密码验证

节点设置密码 1、修改配置文件 在配置文件里面增加密码选项,一定要加上masterauth,不然Redirected的时候会失败。 masterauth redispassword requirepass redispassword 修改后需要重启redis节点。 2、动态修改 连接redis节点进行配置设置,然…

java索引ref_java – 如何使用jgit库将git HEAD指向特定的ref?

我想以编程方式更新HEAD而不对非裸仓库执行checkout或rebase.我希望工作树和索引在操作后保持不变.编辑我需要更新HEAD的符号目标,而不是HEAD当前目标的提交ID.这更像是一个结账,而不是其他任何东西,除了我不能使用org.eclipse.jgit.api.CheckoutCommand因为它需要我更新路径,但…

【codeforces 103E】 Buying Sets

http://codeforces.com/problemset/problem/103/E (题目链接) 题意 给出$n$个数,每个数与一个集合相关联。从其中选出最小的若干个数,选出的数的个数与这些数相关联的集合的并集大小相等。 Solution 因为保证了有完全匹配,所以跑出一个完全匹…

github大学课程_GitHub基础教程:如何使用GitHub课程

github大学课程Learn the basics of GitHub in this tutorial by Tiffany Thompson. You will learn about:在Tiffany Thompson撰写的本教程中,学习GitHub的基础知识。 您将了解: creating a new repository and adding files, 创建一个新的存储库并添加…

进程间通信 (IPC) 方法总结(三)

进程间通信 (IPC) 方法总结(三) 信号量(SEMAPHORE) 信号量是一个计数器,用于多进程对共享数据的访问,信号量的意图在于进程间同步。 为了获得共享资源,进程需要执行下列操…

leetcode1277. 统计全为 1 的正方形子矩阵(dp)

给你一个 m * n 的矩阵,矩阵中的元素不是 0 就是 1,请你统计并返回其中完全由 1 组成的 正方形 子矩阵的个数。示例 1:输入:matrix [[0,1,1,1],[1,1,1,1],[0,1,1,1] ] 输出:15 解释: 边长为 1 的正方形有…

实现离线加域---Windows2008 R2 新功能系列之八

我们都知道,部署活动目录,无非搭建一台或多台DC,然后把其它的客户端计算机或成员服务器全部加入域,但在windows2008SP2以前,客户端加入域时,DC必须在线,而从2008R2开始我们已经可以做到让客户端…

【bzoj1263】[SCOI2006]整数划分 高精度

题目描述 从文件中读入一个正整数n(10≤n≤31000)。要求将n写成若干个正整数之和,并且使这些正整数的乘积最大。 例如,n13,则当n表示为4333(或22333)时,乘积108为最大。 输入 只有一…

rails i18n模型_Rails国际化的完整指南(i18n)

rails i18n模型by Anastasia由Anastasia Rails国际化的完整指南(i18n) (The Complete Guide to Rails Internationalization (i18n)) In this article you are going to learn how to translate your Rails application into multiple languages, work with translations, loc…

分表后需要注意的二三事

前言 本篇是上一篇《一次分表踩坑实践的探讨》,所以还没看过的朋友建议先看上文。 还是先来简单回顾下上次提到了哪些内容: 分表策略:哈希、时间归档等。分表字段的选择。数据迁移方案。而本篇文章的背景是在我们上线这段时间遇到的一些问题并…

DNS 原理

阮老师的作品,非常精彩,转载! DNS 是互联网核心协议之一。不管是上网浏览,还是编程开发,都需要了解一点它的知识。 本文详细介绍DNS的原理,以及如何运用工具软件观察它的运作。我的目标是,读完此…

leetcode1169. 查询无效交易

如果出现下述两种情况,交易 可能无效: 交易金额超过 1000 或者,它和另一个城市中同名的另一笔交易相隔不超过 60 分钟(包含 60 分钟整) 每个交易字符串 transactions[i] 由一些用逗号分隔的值组成,这些值分…

销售员/学员/讲师系统

前言: 今晚写一篇关于学员/讲师/销售员CRM系统。这个小项目是27号开始做的,大概搞了一星期不到。我把一些知识点总结下,还写下当时克服的BUG。 Django练习小项目:学员管理系统设计开发 带着项目需求学习是最有趣和效率最高的,今天…