包装类的 LinkedList 迭代器实现



所以我实现了以下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,但我不太了解如何正确实现迭代器。

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

代码示例或多或少取自此处。

相关内容

  • 没有找到相关文章

最新更新