> For the complete documentation index, see [llms.txt](https://moluo.gitbook.io/notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://moluo.gitbook.io/notes/bian-cheng-xue-xi/java/java-ji-chu/7.5-shi-xian-iterable-jie-kou.md).

# 7.5实现Iterable接口

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

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

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

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

## 实现步骤

1.自定义类实现Iterator接口

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

## 示例：包装链表类，实现Iterable接口

```java
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等信息。

## 所感

* 阅读接口注释，严格按照合约来实现
* 为接口写注释，接口即合约。为接口写注释时，注释应详尽明了。注释信息包含功能、参数、返回值、异常、特殊情况等说明信息。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://moluo.gitbook.io/notes/bian-cheng-xue-xi/java/java-ji-chu/7.5-shi-xian-iterable-jie-kou.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
