包装类的LinkedList迭代器实现

问题描述 投票:0回答:1

所以我实现了以下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);
    }

}

但是,现在我创建了一个LinkedListWrapper数组,并且想要遍历链表的字符串,我显然不能-因为我还没有实现迭代器。我搜索了LinkedList API,但是我没有完全了解如何正确实现Iterator。

java iterator wrapper
1个回答
0
投票

您需要实现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. 
    } 
} 

代码示例或多或少取自here


0
投票

LinkedList类不包含迭代器函数。它是从其超类AbstractSequentialList扩展而来的。您需要检查迭代器方法AbstractSequentialList

下面是我发现的示例代码:

AbstractSequentialList.iterator和listIterator

public Iterator<E> iterator() {
    return listIterator();
}


public abstract ListIterator<E> listIterator(int index);

LinkedList.listIterator

public ListIterator<E> listIterator(int index) {
    checkPositionIndex(index);
    return new ListItr(index);
}
© www.soinside.com 2019 - 2024. All rights reserved.