How can I make my class iterable so I can use foreach syntax?

后端 未结 5 1023
借酒劲吻你
借酒劲吻你 2020-12-16 10:33

I have Book and BookList classes. BookList is something like this:

public class BookList 
{
    private final List<         


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 11:17

    Here we can see the simple implementation of LinkedList with iterator and foreach syntax

    class LinkedList implements Iterable{
        private Node node;
        public void add(Object data){
            if(!Optional.ofNullable(node).isPresent()){
                node = new Node();
                node.setData(data);
            }else{
                Node node = new Node();
                node.setData(data);
                Node lastNode = getLastNode(this.node);
                lastNode.setNext(node);
            }
        }
    
        private Node getLastNode(Node node){
            if(node.getNext()==null){
                return node;
            }else{
                return getLastNode(node.getNext());
            }
        } 
    
        class Node{
            private Object data;
            private Node next;
            public Object getData() {
                return data;
            }
            public void setData(Object data) {
                this.data = data;
            }
            public Node getNext() {
                return next;
            }
            public void setNext(Node next) {
                this.next = next;
            }
        }
    
        public Iterator iterator() {
            return new NodeIterator();
        }
    
        class NodeIterator implements Iterator{
            private Node current;
    
            public boolean hasNext() {
                if(current == null){
                    current = node;
                    return Optional.ofNullable(current).isPresent();
                }else{
                    current = current.next;
                    return Optional.ofNullable(current).isPresent();
                }
            }
    
            public Node next() {
                return current;
            }
        }
    }
    
    public class LinkedListImpl {
        public static void main(String[] args) {
            LinkedList linkedList = new LinkedList();
            linkedList.add("data1");
            linkedList.add("data2");
            linkedList.add("data3");
            for(LinkedList.Node node: linkedList){
                System.out.println(node.getData());
            }
        }
    }
    

提交回复
热议问题