7.5实现Iterable接口

你还在使用如下的形式遍历元素么?

for (int i = 0; i < linkedList.size(); i++) {
    System.out.println(linkedList.get(i));
}

每次遍历都一个姿势,要不解锁个如下新姿势吧。看起来代码更少,更优雅。

for (String s : linkedList) {
    System.out.println(s);
}

实现步骤

1.自定义类实现Iterator接口

2.自定义类实现Iterable接口,并返回步骤一中的自定义Iterator类。

示例:包装链表类,实现Iterable接口

public class LinkedList implements Iterable<Integer>{

    Node head;
    Node tail;

    public LinkedList(){
        head=null;
        tail=null;
    }

    public void add(int value){
        Node node =new Node(value);
        if(tail==null){
            head=node;
        }else{
            tail.setNext(node);
        }
        tail=node;
    }

    @Override
    public Iterator<Integer> iterator(){
        return new ListIterator(head);
    }


    class ListIterator implements Iterator<Integer>{

        Node currentNode;

        public ListIterator(Node head){
            currentNode=head;
        }

        @Override
        public boolean hasNext(){
            return currentNode!=null;
        }

        @Override
        public Integer next(){
            if (currentNode == null){
                throw new NoSuchElementException();
            }
            int value=conrrentNode.getValue();
            currentNode=currentNode.getNext();
            return value;
        }
    }

}

提示:面向接口编程时,请详细阅读接口注释。如在实现Iterator时,我们在注释中获取到hasNext()需返回true|false,next()方法无返回值时需返回NoSuchElementException等信息。

所感

  • 阅读接口注释,严格按照合约来实现

  • 为接口写注释,接口即合约。为接口写注释时,注释应详尽明了。注释信息包含功能、参数、返回值、异常、特殊情况等说明信息。

Last updated

Was this helpful?