迭代中Iterable和Iterator分为两个接口的好处
2012-04-20 15:44
519 查看
主要是分工作业。Iterable告知这个集合可以直接进行遍历;Iterator则是执行具体的遍历操作。而且一个实现Iterable接口的集合可以进行多次的遍历,当每次执行遍历操作的时候把自己本身传给实现Iterator的对象,这样每次遍历的操作都不会影响这个集合的内部元素。
package com.zz.iterator; public class LinkedList<E> implements Collection<E> , Iterable<E>{ private int size = 0; private Node<E> head; private Node<E> tail; public Node<E> getHead() { return head; } public void setHead(Node<E> head) { this.head = head; } public Node<E> getTail() { return tail; } public void setTail(Node<E> tail) { this.tail = tail; } public void add(E e) { Node<E> n = new Node<E>(e,null); if (head == null) { head = n; tail = n; } else { tail.setNext(n); tail = n; } size ++; } public E get(int ix) throws IndexOutOfBoundsException{ if (size <= 0 || size <= ix) { throw new IndexOutOfBoundsException("数组越界了:"+ix); } Node<E> e = head; for (int i=0;i<ix;i++) { e = e.getNext(); } return e.getCurrentE(); } public int size() { return size; } @Override public Iterator<E> iterator() { return new LinkedListIterator<E>(this); } @SuppressWarnings("hiding") public class LinkedListIterator<E> implements Iterator<E> { private int index = 0; private LinkedList<E> linkedList; public LinkedListIterator(LinkedList<E> linkedList) { this.linkedList = linkedList; } @Override public boolean hasNext() { return size > index; } @Override public E next() { Node<E> node = linkedList.getHead(); for (int i=0;i<index;i++) { node = node.getNext(); } index ++; return node.getCurrentE(); } } }
相关文章推荐
- Java迭代 : Iterator和Iterable接口
- Iterator、Iterable接口的使用及详解
- java - 集合框架(一)区分 Iterator 接口 和 Iterable接口
- java中的接口Iterator和Iterable的区别
- python 3-1 如何实现可迭代对象iterable和迭代器对象iterator,__iter__,__getitem__
- Java--Iterator接口和Iterable接口详解
- Java--Iterator接口和Iterable接口详解
- java为什么不直接实现Iterator接口,而是实现Iterable
- Java--Iterator接口和Iterable接口详解
- Java--Iterator接口和Iterable接口详解
- Python教程学习简记7--Python 可迭代对象:Iterable ,迭代器:Iterator
- 源码分析-java-Iterator接口和Iterable<T>接口
- iterable和iterator接口的区别
- Java--Iterator接口和Iterable接口详解
- Java--Iterator接口和Iterable接口详解
- 迭代 Iterable与Iterator
- 接口 Iterator<E> 与 接口 Iterable<T>
- Java--Iterator接口和Iterable接口详解
- 桥接模式(把接口和实现分为两个继承树,而不是将实现来继承接口,造成实现和接口耦合
- PYTHON 中 ITERATOR(迭代器)和ITERABLE(可迭代)的区别