Iterator 和 Iterable 接口的区别

本文深入解析Java集合框架的核心概念:Iterable接口与Iterator接口的区别及应用。通过实例展示如何使用这两种接口进行集合操作,并解释为何集合类实现Iterable而非Iterator。
java.lang.Iterable 
java.util.Iterator 

来自百度知道: 
Iterator是迭代器类,而Iterable是接口。 
好多类都实现了Iterable接口,这样对象就可以调用iterator()方法。 
一般都是结合着用,比如 
HashMap类就实现了Iterable接口,而要访问或打印出Map中所有内容时,就可以这样: HashMap hashMap; 
Iterator iter = hashMap.iterator(); 
while(iter.hashNext()) { 
  String s = iter.next(); 


转至:http://liuyun025.iteye.com/blog/1321045 
为什么一定要实现Iterable接口,为什么不直接实现Iterator接口呢? 
      看一下JDK中的集合类,比如List一族或者Set一族,都是实现了Iterable接口,但并不直接实现Iterator接口。 
仔细想一下这么做是有道理的。 

      因为Iterator接口的核心方法next()或者hasNext() 是依赖于迭代器的当前迭代位置的。 
      如果Collection直接实现Iterator接口,势必导致集合对象中包含当前迭代位置的数据(指针)。 
      当集合在不同方法间被传递时,由于当前迭代位置不可预置,那么next()方法的结果会变成不可预知。 
      除非再为Iterator接口添加一个reset()方法,用来重置当前迭代位置。 
      但即时这样,Collection也只能同时存在一个当前迭代位置。 
      而Iterable则不然,每次调用都会返回一个从头开始计数的迭代器。 

      多个迭代器是互不干扰的。

Java集合类库将集合的接口与实现分离。同样的接口,可以有不同的实现。

Java集合类的基本接口是Collection接口。而Collection接口必须实现Iterator接口。

以下图表示集合框架的接口,java.lang以及java.util两个包里的。红色字体部分是OCJP考纲要求的接口。其他部分可以从左向右看,比如Collection的Subinterfaces有List,Set以及Queue等。


Iterator接口

Iterator接口包含三个方法:

[java]  view plain copy
  1.   public interface Iterator<E>{  
  2.     E next();  
  3.     boolean hasNext();  
  4.     void remove();  
  5. }  
以下例子是利用了Iterator接口的着三个方法,实现遍历ArrayList<String>类型。

  • 一开始迭代器在所有元素的左边,调用next()之后,迭代器移到第一个和第二个元素之间,next()方法返回迭代器刚刚经过的元素。
  • hasNext()若返回True,则表明接下来还有元素,迭代器不在尾部。
  • remove()方法必须和next方法一起使用,功能是去除刚刚next方法返回的元素。

[java]  view plain copy
  1. package com.xujin;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.Collection;  
  5. import java.util.Iterator;  
  6.   
  7. public class Test{  
  8.     public static void main(String...arg){  
  9.         Collection<String> a = new ArrayList<String>();  
  10.         a.add("Bob");  
  11.         a.add("Alice");  
  12.         a.add("Lisy");  
  13.           
  14.         Iterator<String> iter = a.iterator();  
  15.         while(iter.hasNext()){  
  16.             String ele = iter.next();  
  17.             System.out.print(ele + "  ");//Bob  Alice  Lisy    
  18.         }  
  19.         System.out.println();  
  20.           
  21.         System.out.println(a);//[Bob, Alice, Lisy]  
  22.         Iterator<String> iter2 = a.iterator();  
  23.         iter2.next();  
  24.         iter2.remove();  
  25.         System.out.println(a);//[Alice, Lisy]  
  26.           
  27.     }  
  28. }  


Iterable接口

Iterable接口仅包含一个方法:

[java]  view plain copy
  1. public interface Iterable<E>{  
  2.     Iterator<E> iterator();  
  3. }  

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类来编写具体的类。

以下类都实现了Collection接口:

AbstractCollection, AbstractList, AbstractQueue, AbstractSequentialList, AbstractSet, ArrayBlockingQueue, ArrayDequeArrayList, AttributeList, BeanContextServicesSupport, BeanContextSupport, ConcurrentLinkedDeque,ConcurrentLinkedQueue, ConcurrentSkipListSet, CopyOnWriteArrayList, CopyOnWriteArraySet, DelayQueue, EnumSetHashSet, JobStateReasons, LinkedBlockingDeque, LinkedBlockingQueue, LinkedHashSetLinkedList,LinkedTransferQueue, PriorityBlockingQueue, PriorityQueue, RoleList, RoleUnresolvedList, Stack, SynchronousQueue, TreeSet, Vector



Collection接口有三个常用的子接口,分别是List,Set,Queue。


<think>好的,我需要回答用户关于Java中IteratorIterable接口区别的问题。首先,我得回忆这两个接口的基本定义用途。根据提供的引用资料,Iterable接口有一个iterator()方法,返回Iterator实例。而Iterator接口则定义了hasNext()、next()remove()方法,用于遍历集合。 接下来,用户想知道两者的区别以及为什么Java要这样设计。我需要解释设计上的考虑,比如Iterable允许集合支持多种遍历方式,通过不同的Iterator实现类来实现,比如LinkedList的ListItrDescendingIterator。同时,分开这两个接口可以更灵活,符合单一职责原则。 然后,要比较它们的用法差异。例如,Iterable让集合可以使用for-each循环,而Iterator需要显式地使用hasNext()next()方法。还要提到在什么情况下使用哪种接口,比如需要移除元素时只能用Iterator的remove()方法。 另外,用户可能对为什么不让集合直接实现Iterator接口有疑问。根据引用34,主要是因为一个集合可能有多种遍历方式,每个遍历需要不同的Iterator实例,保持遍历状态独立。如果集合自己实现Iterator,会导致状态混乱,无法同时进行多个遍历。 需要确保回答结构清晰,分点说明区别、设计原因用法示例。同时,要引用提供的资料,比如引用4中提到的LinkedList的例子,以及后缀语法上的区别。最后生成相关问题,帮助用户进一步学习。 检查是否遵循了系统级指令:数学公式没问题,这里不需要。代码块用正确格式,用户问题中的代码示例已经给出。使用中文,结构清晰。引用资料在末尾标注,例如[^4]。然后生成相关问题,放在最后。</think>### Java中IteratorIterable接口区别及用法 #### 1. **接口定义与核心功能** - **Iterable** 定义在`java.lang`包中,仅包含一个方法: ```java public interface Iterable<T> { Iterator<T> iterator(); } ``` 实现此接口的类(如集合类)可通过`iterator()`方法返回一个**Iterator实例**,支持迭代操作。同时,它允许对象使用增强型`for-each`循环[^1][^4]。 - **Iterator** 定义在`java.util`包中,提供遍历集合的核心方法: ```java public interface Iterator<E> { boolean hasNext(); E next(); default void remove() { /*...*/ } } ``` 它负责具体的遍历逻辑(如顺序、逆序)状态管理(如当前元素位置)[^2]。 --- #### 2. **设计区别与原因** - **职责分离** - **Iterable**:表示“可迭代的”,强调集合支持遍历的能力。 - **Iterator**:表示“迭代器”,定义具体的遍历方式。 这种分离使得一个集合可以支持**多种遍历方式**。例如,`LinkedList`可提供正向遍历的`ListItr`逆向遍历的`DescendingIterator`两种迭代器。 - **状态独立性** 每次调用`iterator()`会生成新的迭代器实例,保证不同遍历操作的状态互不干扰。若集合直接实现`Iterator`,则多个遍历会共享状态,导致逻辑混乱[^3]。 --- #### 3. **用法对比** - **Iterable的典型用法** 通过`for-each`循环隐式调用迭代器: ```java List<String> list = new ArrayList<>(); for (String s : list) { // 底层调用list.iterator() System.out.println(s); } ``` - **Iterator的显式操作** 直接控制遍历过程,适用于需要动态修改集合的场景(如删除元素): ```java Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); if (s.isEmpty()) { it.remove(); // 安全删除当前元素 } } ``` [^2] --- #### 4. **关键区别总结** | 特性 | Iterable | Iterator | |---------------------|-------------------------------|------------------------------| | **接口目标** | 声明集合可被迭代 | 定义具体遍历逻辑 | | **方法功能** | 生成迭代器实例 | 实现遍历、状态管理 | | **设计目的** | 支持多种遍历方式 | 提供单一遍历逻辑 | | **与集合的关系** | 集合直接实现 | 通过Iterable间接获取 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值