本文主要是介绍迭代中Iterable和Iterator分为两个接口的好处,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
主要是分工作业。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;}@Overridepublic 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;} @Overridepublic boolean hasNext() {return size > index;}@Overridepublic E next() {Node<E> node = linkedList.getHead();for (int i=0;i<index;i++) {node = node.getNext();}index ++;return node.getCurrentE();}}
}
这篇关于迭代中Iterable和Iterator分为两个接口的好处的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!