Reputation: 13
I created an interface called LLIterator that extends iterator and add two methods to it, when i tried to use it in one of my class, I couldn't compile it. Here is what I got. my custom interface is like this:
import java.util.Iterator;
public interface LLIterator<T> extends Iterator<T>{
boolean hasNext();
T next();
void remove();
void addBefore(T element);
void addAfter(T element);
}
my linkedlist is like this:
import java.lang.StringBuilder;
import java.util.NoSuchElementException;
import java.util.Iterator;
import java.util.ArrayList;
/**
* A class to represent a linked list of nodes.
*/
public class LinkedList<T> implements Iterable<T>{
/** the first node of the list, or null if the list is empty */
private LLNode<T> first;
/** some codes here
@Override
public LLIterator<T> iterator() {
return new LinkedListIterator();
}
private class LinkedListIterator implements LLIterator<T>{
LLNode<T> nodeptr = first;
final LinkedList<T> list = getList();
@Override
public void addBefore(T element){
if(nodeptr == first || list.isEmpty()){
throw new NoSuchElementException();
}
LLNode<T> newnode = new LLNode<T>(element, null);
newnode.setNext(nodeptr);
}
@Override
public void addAfter(T element){
LLNode<T> newnode;
if(nodeptr == first || list.isEmpty()){
newnode = new LLNode<T>(element, null);
list.setFirst(newnode);
}
newnode = new LLNode<T>(element, null);
newnode.setNext(nodeptr.getNext());
nodeptr.setNext(newnode);
}
}
in another class, i used iterator method of the this Linkedlist
and called addBefore
method, however when I compile it, it shows
cannot find symbol
symbol: method addAfter(WordData)
location: variable iterator of type java.util.Iterator<WordData>
here is part of my another class:
public void addFollowingWord(String word){
Iterator<WordData> iterator = list.iterator();
WordData current = iterator.next();
while(iterator.hasNext()){
if(current.getWord().equals(word)){
current.incrementCount();
}
else if(current.getWord().compareTo(word) < 0){
current = iterator.next();
}
else if(current.getWord().compareTo(word) > 0){
WordData newword = new WordData(word);
iterator.addBefore(newword);
}
}
if(!iterator.hasNext()){
WordData newword = new WordData(word);
iterator.addAfter(newword);
}
}
I'm very confused, did I make any mistake somewhere or I missed something?
Upvotes: 0
Views: 107
Reputation: 50716
You can't access the methods on the custom interface because it's cast as Iterator
. Update your iterator()
method to return your subinterface:
@Override
public LLIterator<T> iterator() {
return new LinkedListIterator();
}
Upvotes: 4