Iterator、Iterable接口的使用及详解
Java集合类库将集合的接口与实现分离。同样的接口,可以有不同的实现。
Java集合类的基本接口是Collection接口。而Collection接口必须实现Iterator接口。
以下图表示集合框架的接口,java.lang以及java.util两个包里的。其他部分可以从左向右看,比如Collection的Subinterfaces有List,Set以及Queue等。
package java.util;/*** An iterator over a collection. Iterator takes the place of Enumeration in* the Java collections framework. Iterators differ from enumerations in two* ways: <ul>* <li> Iterators allow the caller to remove elements from the* underlying collection during the iteration with well-defined* semantics.* <li> Method names have been improved.* </ul><p>** This interface is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html">* Java Collections Framework</a>.** @author Josh Bloch* @version %I%, %G%* @see Collection* @see ListIterator* @see Enumeration* @since 1.2*/ public interface Iterator<E> {/*** Returns <tt>true</tt> if the iteration has more elements. (In other* words, returns <tt>true</tt> if <tt>next</tt> would return an element* rather than throwing an exception.)** @return <tt>true</tt> if the iterator has more elements.*/boolean hasNext();/*** Returns the next element (每一次迭代,the next element就是index为0的元素)in the iteration.** @return the next element in the iteration.* @exception NoSuchElementException iteration has no more elements.*/E next();/*** * Removes from the underlying collection the last element returned by the* iterator (optional operation). This method can be called only once per* call to <tt>next</tt>. 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.** @exception UnsupportedOperationException if the <tt>remove</tt>* operation is not supported by this Iterator.* @exception IllegalStateException if the <tt>next</tt> method has not* yet been called, or the <tt>remove</tt> method has already* been called after the last call to the <tt>next</tt>* method.*/void remove(); }
以下例子是利用了Iterator接口的着三个方法,实现遍历ArrayList<String>类型。
一开始迭代器在所有元素的左边,调用next()之后,迭代器移到第一个和第二个元素之间,next()方法返回迭代器刚刚经过的元素。
hasNext()若返回True,则表明接下来还有元素,迭代器不在尾部。
remove()方法必须和next方法一起使用,功能是去除刚刚next方法返回的元素。
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator;public class ForEachDemo {public static void main(String... arg) {Collection<String> a = new ArrayList<String>();a.add("Bob");a.add("Alice");a.add("Lisy");Iterator<String> iterator = a.iterator();while (iterator.hasNext()) {String ele = iterator.next();System.out.println(ele);//Bob Alice Lisy }System.out.println(a);//[Bob, Alice, Lisy] iterator = a.iterator();iterator.next();iterator.remove();System.out.println(a);//[Alice, Lisy] } }
package java.lang;import java.util.Iterator;/** Implementing this interface allows an object to be the target of* the "foreach" statement.* @since 1.5*/ public interface Iterable<T> {/*** Returns an iterator over a set of elements of type T.* * @return an Iterator.*/Iterator<T> iterator(); }
for-each循环可以与任何实现了Iterable接口的对象一起工作。
而Collection接口扩展了Iterable接口,故标准类库中的任何集合都可以使用for-each循环。
Collection接口
此接口的方法
public interface Collection<E>{......}
Modifier and Type | Method and Description |
---|---|
boolean
|
add(E e)
Ensures that this collection contains the specified element (optional operation).
|
boolean
|
addAll(Collection<? extends E> c)
Adds all of the elements in the specified collection to this collection (optional operation).
|
void
|
clear()
Removes all of the elements from this collection (optional operation).
|
boolean
|
contains(Object o)
Returns true if this collection contains the specified element.
|
boolean
|
containsAll(Collection<?> c)
Returns true if this collection contains all of the elements in the specified collection.
|
boolean
|
equals(Object o)
Compares the specified object with this collection for equality.
|
int
|
hashCode()
Returns the hash code value for this collection.
|
boolean
|
isEmpty()
Returns true if this collection contains no elements.
|
Iterator<E>
|
iterator()
Returns an iterator over the elements in this collection.
|
boolean
|
remove(Object o)
Removes a single instance of the specified element from this collection, if it is present (optional operation).
|
boolean
|
removeAll(Collection<?> c)
Removes all of this collection's elements that are also contained in the specified collection (optional operation).
|
boolean
|
retainAll(Collection<?> c)
Retains only the elements in this collection that are contained in the specified collection (optional operation).
|
int
|
size()
Returns the number of elements in this collection.
|
Object[]
|
toArray()
Returns an array containing all of the elements in this collection.
|
<T> T[]
|
toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array.
|
因为其中有一个返回值为Iterator<E>类型的iterator()方法,所以,Collection接口必须实现Iterator接口
实现Collection接口的每一个类都要实现以上众多方法,但开发者自己实现很麻烦。所以java提供了AbstractCollection类来编写具体的类。
java.util
Interface Collection<E>
- All Superinterfaces:
- Iterable<E>
- All Known Subinterfaces:
- BeanContext, BeanContextServices, BlockingDeque<E>, BlockingQueue<E>, Deque<E>, List<E>, NavigableSet<E>, Queue<E>, Set<E>,SortedSet<E>
- All Known Implementing Classes:
- AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDeque, ArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet,DelayQueue, EnumSet, HashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSet, LinkedList, PriorityBlockingQueue,PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector
Collection接口有三个常用的子接口,分别是List,Set,Queue。
http://blog.csdn.net/xujinsmile/article/details/8543544
看一下JDK中的集合类,比如List一族或者Set一族,
都是实现了Iterable接口,但并不直接实现Iterator接口。
仔细想一下这么做是有道理的。因为Iterator接口的核心方法next()或者hasNext()
是依赖于迭代器的当前迭代位置的。
如果Collection直接实现Iterator接口,势必导致集合对象中包含当前迭代位置的数据(指针)。
当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。
除非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。
但即时这样,Collection也只能同时存在一个当前迭代位置。
而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。
多个迭代器是互不干扰的。
http://www.cnblogs.com/highriver/archive/2011/07/27/2077913.html
import java.util.Iterator;public class ForEachAPIDemo {public static void main(String[] args) throws Exception {Students students = new Students(10);for (Student student : students) {System.out.println(student.getSid() + ":" + student.getName());}} }// 支持for each迭代循环的学生集合类 class Students implements Iterable<Student> {// 存储所有学生类的数组private Student[] students;// 该构造函数可以生成指定大小的学生类变量数组,并初始化该学生类变量数组public Students(int size) {students = new Student[size];for (int i = 0; i < size; i++) {students[i] = new Student(String.valueOf(i), "学生" + String.valueOf(i));}}@Overridepublic Iterator<Student> iterator() {return new StudentIterator();}// 实现Iterator接口的私有内部类,外界无法直接访问private class StudentIterator implements Iterator<Student> {// 当前迭代元素的下标private int index = 0;// 判断是否还有下一个元素,如果迭代到最后一个元素就返回falsepublic boolean hasNext() {return index != students.length;}@Overridepublic Student next() {return students[index++];}// 这里不支持,抛出不支持操作异常public void remove() {throw new UnsupportedOperationException();}} }class Student {private String sid;private String name;public Student(String sid, String name) {setSid(sid);setName(name);}public String getSid() {return sid;}public void setSid(String sid) {this.sid = sid;}public String getName() {return name;}public void setName(String name) {this.name = name;}@Overridepublic String toString() {return "Student{" +"sid='" + sid + '\'' +", name='" + name + '\'' +'}';} }
转载于:https://www.cnblogs.com/writeLessDoMore/p/6881480.html
Iterator、Iterable接口的使用及详解相关推荐
- STM32接口FSMC/FMC难点详解
STM32接口FSMC/FMC难点详解 转载 http://blog.sina.com.cn/s/blog_808bca130102x94k.html STM32F767的FMC将外部存储器划分为 ...
- php支付宝接口参数错误,php支付接口_php支付宝支付接口程序及参数详解
摘要 腾兴网为您分享:php支付宝支付接口程序及参数详解,作业盒子,智能互联,智联招聘,小番茄等软件知识,以及雷电游戏中心,天气预报软件,live电视直播,otcbtc,手机街机,lq-630k驱动 ...
- Collection集合类和Map接口各实现类详解
Java的集合类(collection接口和Map) 一.集合概述 集合:集合是java中提供的一种容器,可以用来存储多个数据. 集合和数组既然都是容器,它们有啥区别呢? 数组的长度是固定的.集合的长 ...
- C#接口归纳总结实例详解
本篇文章通过实例代码对接口做了详解,需要的朋友可以参考下 C#接口的学习,在编程中,我们经常会用到接口,那什么是接口呢? 接口描述的是可属于任何类或结构的一组相关功能,所以实现接口的类或结构必须实现接 ...
- loopback接口、router ID详解
目录 loop back接口简介: loopback接口应用: router id 简介: 选举规则: loop back接口简介: loopback接口是一种纯软件性质的虚拟接口.loopback接 ...
- java切面不需要接口了吗_详解Spring AOP 实现“切面式”valid校验
why: 为什么要用aop实现校验? answer: spring mvc 默认自带的校验机制 @Valid + BindingResult, 但这种默认实现都得在Controller方法的中去接收B ...
- 232接口针脚定义_详解串口通信232/485/422,一文就可以搞定!
一.RS232基础知识 计算机与计算机或计算机与终端之间的数据传送可以采用串行通讯和并行通讯二种方式.由于串行通讯方式具有使用线路少.成本低,特别是在远程传输时,避免了多条线路特性的不一致而被广泛采用 ...
- 接口测试之HTTP协议详解
引言 HTTP是一个属于应用层的面向对象的协议,由于其简捷.快速的方式,适用于分布式超媒体信息系统.它于1990年提出,经过几年的使用与发展,得到不断地完善和扩展.目前在WWW中使用的是HTTP/1. ...
- python+requests接口自动化测试框架实例详解教程(米兔888)
来源:https://my.oschina.net/u/3041656/blog/820023 源码:https://pan.baidu.com/s/1lgIEToiczTvvjy--p-N20g 提 ...
最新文章
- 美团工程师上演“谍战”剧?“黑了一把”拼多多获取薪资信息
- display none 隐藏后怎么显示_web前端入门到实战:元素显示隐藏的9种思路
- git 多仓库源 配置
- 手动调用cx-table.focus和a.focus方法的效果比较
- 360网络修复工具_Win10网络图标不见了解决方法
- Java用TCP手写聊天室 可以 私聊版加群聊版
- [原创]Scala学习:编写Scala脚本
- c语言随机产生10个30 100,c语言编写随机产生10个100~200之间整数,幷按从大到小排序...
- [设计模式-结构型]代理模式(Proxy)
- Python入门--为什么将元组设计为不可变序列
- 11.性能之巅 洞悉系统、企业与云计算 --- 云计算
- 大数乘法与大数加法 java实现
- docker privileged作用_docker容器性能监控cAdvisor+influxDB+grafana监控系统安装部署
- 欧姆龙PLC以太网modbusTCP通讯
- office 2010安装包
- windows系统下压力测试工具(cpu使用率,内存使用率,磁盘使用率,磁盘空间)
- SQL 注入防御方法总结
- 明星也爱字体——赵丽颖秀气字体:(江湖少女两版)蓄势待发
- Android NFC基础
- PS使得背景变成白色但是使得黑色字体颜色加深
热门文章
- 支持大数据渲染下拉列表组件开发 SuperSelect(基于antd Select)
- 乐乐茶完成近2亿元Pre-A轮融资,祥峰投资领投
- 前端、git入门至常用指令
- ant-design-pro Login 中的 UserName 和 Password 的验证规则 rules
- libtool: line 454 CDPATH libtool: line 1132: func_opt_split: : command not found
- Exchange2010 控制台提示您的权限不足,无法查看此数据
- 下载SpringJar包
- zzzp0371 属于本人
- 使用DDMS抓取安卓APP的奔溃日志
- 一年春事,桃花红了谁……