因此,我实现了以下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。 最佳答案 您需要实现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。关于java - 包装器类的LinkedList迭代器实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59322303/
10-17 01:30