简体   繁体   English

包装类的 LinkedList 迭代器实现

[英]LinkedList iterator implementation for a wrapper class

So I implemented the following LinkedList wrapper class:所以我实现了以下 LinkedList 包装类:

import java.util.LinkedList;
import java.util.ListIterator;

public class LinkedListWrapper {

    private LinkedList<String> listWrapper;

    public LinkedListWrapper(){
        this.listWrapper = new LinkedList<String>();
    }

    /**
     * Method to check if the linked list contains the string object.
     * @param str String object to check if the list contains.
     * @return True if the list contains it and false otherwise.
     */

    public boolean contains(String str){
        return this.listWrapper.contains(str);
    }

    /**
     * Method to add a String object to the list.
     * @param str String object to add.
     * @return True if the item was added and false otherwise.
     */

    public boolean add(String str){
        if(!this.contains(str)){
            this.listWrapper.add(str);
        }
        return false;
    }


    /**
     * Method to delete str object
     * @param str String object to delete
     * @return True if str was deleted and false otherwise.
     */

    public boolean delete(String str){
        return this.listWrapper.remove(str);
    }

}

However, Now that I create an array of LinkedListWrapper and I want to iterate through the linked list's strings, I obviously can't - because I haven't implemented an iterator.但是,既然我创建了一个 LinkedListWrapper 数组并且我想遍历链表的字符串,我显然不能 - 因为我还没有实现迭代器。 I searched the LinkedList API But I didn't quite get how to implement the Iterator properly.我搜索了LinkedList API但我不太明白如何正确实现迭代器。

You need to implement the Interable<> interface and override its methods :您需要实现 Interable<> 接口并覆盖其方法:

    class LinkedListWrappe implements Iterable<> { 

    // code for data structure 
    public Iterator<> iterator() { 
        return new CustomIterator<>(this); 
    } 
} 
class CustomIterator<> implements Iterator<> { 

    // constructor 
    CustomIterator<>(CustomDataStructure obj) { 
        // initialize cursor 
    } 

    // Checks if the next element exists 
    public boolean hasNext() { 
    } 

    // moves the cursor/iterator to next element 
    public T next() { 
    } 

    // Used to remove an element. Implement only if needed 
    public void remove() { 
        // Default throws UnsupportedOperationException. 
    } 
} 

Code example is more or less taken from here .代码示例或多或少来自此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM