基础&java|实现Tterable接口

版权声明:本文为博主原创文章,未经允许不得转载。 https://blog.csdn.net/qq_24672657/article/details/82945135

基础&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
 * @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);
        }


    }


}

猜你喜欢

转载自blog.csdn.net/qq_24672657/article/details/82945135
今日推荐