0
我是Java新手,我正在嘗試瞭解迭代器的Iterable &的實現。Iterable&Iterator實現問題(JAVA)
import java.util.Iterator;
import java.util.LinkedList;
import java.util.NoSuchElementException;
public class ClassMates implements Iterable{
private String className;
private LinkedList<String> nameList;
public ClassMates(String className){
this.className = className;
this.nameList = new LinkedList<String>();
}
public void addName(String name){
nameList.add(name);
}
public LinkedList<String> getNameList() {
return nameList;
}
@Override
public Iterator<String> iterator() {
return new IteratorClass();
}
// Inner Class
private class IteratorClass implements Iterator<String>{
private int index;
public IteratorClass(){
this.index = 0;
}
@Override
public boolean hasNext() {
return index < nameList.size();
}
@Override
public String next() {
if(hasNext()){
int i = index;
index++;
System.out.println("This is "+ i);
return nameList.get(i);
}
throw new NoSuchElementException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
}
我的問題是:當我完成實施和嘗試應用的for-each的「迭代」的對象,編譯器說類型不匹配。
這裏是在main()執行的申請,每個:
public class Main {
public static void main(String[] args) {
ClassMates classMates = new ClassMates("03-01");
classMates.addName("Classmate 1");
classMates.addName("Classmate 2");
classMates.addName("Classmate 3");
classMates.addName("Classmate 4");
for(String name : classMates){
//HERE! the compiler report "String" is not match the return type of "classMates"
System.out.println(name);
}
}
任何人都可以點我出了問題?
謝謝!!!
感謝delephin! 當我瀏覽API後,我注意到我應該用替換。 感謝您的快速幫助! –
樂於幫助,歡迎來到堆棧溢出。如果此答案或任何其他人解決了您的問題,請將其標記爲已接受。 – delephin