手敲一个能实现迭代的类

对于一些没有索引的数据结构,不能直接使用foreach循环遍历,但是实现Iterator接口之后就能使用foreach遍历,简化遍历。

1.实现步骤分析

1.先让目标类实现Iterable接口,重写iterator方法

public interface Iterable<T> {
    /**
     * Returns an iterator over elements of type {@code T}.
     *
     * @return an Iterator.
     */
    Iterator<T> iterator();

2.在目标类内部提供一个内部类实现Iterator接口,重写hasNext方法和next方法;

public interface Iterator<E> {
    /**
     * Returns {@code true} if the iteration has more elements.
     * (In other words, returns {@code true} if {@link #next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
    boolean hasNext();

    /**
     * Returns the next element in the iteration.
     *
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iteration has no more elements
     */
    E next();

2.代码实现

类名 AList
构造方法 AList():创建AList对象
成员方法 public int length():获取链表的长度
public void insert(T t):向链表尾部插入一个元素
成员内部类 private class Node:结点类
private class LIterator implements Iterator:实现Iterator接口的内部类
成员变量 private Node head:链表头结点
private int N:链表长度
package test;


import java.util.Iterator;

public class AList<T> implements Iterable<T>{

    //头结点
    private Node head;
    //链表的长度
    private int N;

    public AList(){
        //初始化头结点
        head = new AList.Node(null,null);
        N = 0;
    }


    //获取链表的长度
    public int length(){
        return N;
    }


    //向链表中添加元素t
    public void insert(T t){
        //找到当前链表最后一个结点
        AList.Node n = head;
        while (n.next!=null){
            n = n.next;
        }
        //新建一个结点作为新的最后一个结点
        Node newNode = new Node(t,null);
        //将上一个结点指向最后一个结点
        n.next = newNode;
        //链表长度+1
        N++;
    }

    //结点类
    private class Node {
        //存储数据
        T item;
        //下一个结点
        Node next;

        //构造器
        public Node(T item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

    @Override
    public Iterator iterator(){
        return new LIterator();
    }

    private class LIterator implements Iterator<T>{
        private Node n;

        public LIterator(){
        		//从头结点开始遍历
            this.n = head;
        }
        @Override
        public boolean hasNext() {
            return n.next != null;
        }

        @Override
        public T next() {
            n = n.next;
            return (T)n.item;
        }
    }


    //测试代码
    public static void main(String[] args) {
        AList<String> list = new AList<>();
        list.insert("张三");
        list.insert("李四");
        list.insert("王五");

        //遍历
        for (String each:list){
            System.out.println(each);
        }
    }
}

上一篇:还让业务操作记录影响接口性能?


下一篇:集合类 Collection接口