for (int i = 0; i < linkedList.size(); i++) {
System.out.println(linkedList.get(i));
}
for (String s : linkedList) {
System.out.println(s);
}
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等信息。