基礎&java|實現Tterable介面
阿新 • • 發佈:2018-12-13
基礎&java|實現Iterable介面
Node.java
/**
* @ClassName Node
* @Description TODO
* @Version 1.0
**/
public class Node {
private final Integer vaule;
private Node nextNode;
public Node(Integer vaule) {
this.vaule = vaule;
}
public Integer getVaule() {
return vaule;
}
public Node getNextNode() {
return nextNode;
}
public void setNextNode(Node nextNode) {
this.nextNode = nextNode;
}
public static void printLinkedList(Node node) {
while (node != null) {
System.out.print(node.getVaule());
System. out.print(" ");
node = node.nextNode;
}
System.out.println();
}
}
LinkedList.java
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* @ClassName LinkedList
* @Description TODO
* @Version 1.0
**/
public class LinkedList implements Iterable< Integer> {
Node head;
Node tail;
public LinkedList(){
this.head = null;
this.tail = null;
}
public void add(int vaule){
Node node = new Node(vaule);
if (tail == null) {
head = node;
} else {
tail.setNextNode(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 = currentNode.getVaule();
currentNode = currentNode.getNextNode();
return value;
}
}
}
Test.java
/**
* @ClassName Test
* @Description TODO
* @Author ChenLiLin
* @Date 2018/10/5 下午4:25
* @Version 1.0
**/
public class Test {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
for (int i = 0;i<100;i++) {
linkedList.add(i);
}
for (Integer i : linkedList){
System.out.println(i);
}
}
}