迭代中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;
	}

	@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();
		}
		
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值