簡體   English   中英

我怎樣才能做一個好的迭代器

[英]How can I make a good Iterator

有沒有人知道這段代碼,問題出在哪里

import java.util.Iterator;
import java.util.NoSuchElementException;

public class AlbumIterator implements Iterator<Fotoablum>{
    Fotoalbum album;
    Foto aktuell;
    
    public AlbumIterator(Fotoalbum album){
        this.album=album;
        this.aktuell=aktuell;
    }
    public boolean hasNext(){
        if(this.aktuell == null){
            return true;
        }else{
            return this.aktuell.getNächstes() != null;
        }
    }
    public Foto next(){
        if(this.aktuell == null){
            this.aktuell = this.ablum.erstesFoto;
            return this.aktuell;
        }
        if(this.aktuell.getNächstes() == null){
            throw new NoSuchElementException("Keine weiteren Elemente vorhanden");
        }else{
            this.aktuell = this.aktuell.getNächstes();
            return this.aktuell;
        }
    }
    public void remove() {
        throw new UnsupportedOperationException("Diese Aktion wird nicht unterstützt.");
    }
    public static void main(String[] args){
        return;
    }
}

錯誤信息

AlbumIterator.java:5: error: cannot find symbol
public class AlbumIterator implements Iterator<Fotoablum>{
                                               ^
  symbol: class Fotoablum
AlbumIterator.java:22: error: cannot find symbol
            this.aktuell = this.ablum.erstesFoto;
                               ^
  symbol: variable ablum

這是關於 java 迭代器的作業。 試了很多次,還是錯了,如何才能讓它工作,我需要一個主function嗎?

使用流的更簡單的解決方案

您可以省去麻煩並從Stream創建一個:

Iterator<Foto> it =
Stream.iterate(
         album.erstesFoto, 
         f -> f.getNächstes() != null, 
         f -> f.getNächstes())
      .iterator();

你的具體編譯問題

AlbumIterator.java:5: error: cannot find symbol public class AlbumIterator implements Iterator<Fotoablum>{ ^ symbol: class Fotoablum

我的 German-fu 說您的 class 名稱中有錯字,但是,您的意思是要遍歷Foto ,而不是Fotoalbum

 AlbumIterator.java:22: error: cannot find symbol this.aktuell = this.ablum.erstesFoto; ^ symbol: variable ablum

同樣的錯字,這次是局部變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM