0

の線形検索を実行しようとしていますlinked list。1 つの検索は byintで、もう1 つはStringです。私は何を間違っていますか?**推奨事項に基づいてコードを更新しました。

メイン内

    public static LinkedList<Contributor> contributorList = new LinkedList<>();

        String searchKey = "Jones";
        int intSearchKey = 45;

        System.out.println("Search key " + searchKey + " is found? " + sequentialSearch(contributorList, searchKey));

        System.out.println("Search key " + intSearchKey + " is found? " + sequentialSearch(contributorList, intSearchKey));



Called methods    



    public static <Contributor> boolean sequentialSearch(Iterable<Contributor> contributorList, int intSearchKey) {
    Iterator<Contributor> iter = contributorList.iterator();
    while (iter.hasNext()) {
        if (iter.next().equals(intSearchKey)) {
            return true;
        }
        iter = (Iterator<Contributor>) iter.next();
    }
    return false;
}

public static <Contributor> boolean sequentialSearch(Iterable<Contributor> contributorList, String searchKey) {
    Iterator<Contributor> iter = contributorList.iterator();
    while (iter.hasNext()) {
        if (iter.next().equals(searchKey)) {
            return true;
        }
        iter = (Iterator<Contributor>) iter.next();
    }
    return false;
}
4

2 に答える 2

1

この行は、Contributor オブジェクトを String と比較します。

if (iter.next().equals(searchKey)) {

Contributor オブジェクトが表示されない場合、このようなものが必要になると思います

if (iter.next().getKey().equals(searchKey)) {

また、この行は意味がありません:

 iter = (Iterator<Contributor>) iter.next();

iter.next() はイテレータではなく要素の型を返します

于 2015-08-03T21:43:47.500 に答える
1

ここにあるコードを見てください:

Iterator<Contributor> iter = contributorList.iterator();
while (iter.hasNext()) {
    if (iter.next().equals(intSearchKey)) {
        return true;
    }
    iter = (Iterator<Contributor>) iter.next();
}

への最初の呼び出しでは、オブジェクト.next()が返されることを期待していることに注意してください。Contributor2 番目のケースでは、に変換できるものを返すことを期待していますIterator<Contributor>

Java でイテレータがどのように機能するかについて根本的な誤解があると思います。それがコードが機能しない理由です。イテレーターの.next()メソッドは、イテレーターを自動的に進めます (レシーバーを変更します)。反復されるコレクション内の次の値を返します。これは、互換性のない型があるため、 をiter呼び出すときに新しい値を割り当てるべきではないことを意味します。.next()むしろ、おそらく次のようにコードを構成する必要があります。

Iterator<Contributor> iter = contributorList.iterator();
while (iter.hasNext()) {
    Contributor currElem = iter.next();
    if (currElem.equals(intSearchKey)) {
        return true;
    }
}

値を取得するためにループ内で 1 回だけ呼び出し.next()てから、現在のループ反復でその値を使用することに注意してください。を繰り返し呼び出すと、 は自動的にコレクションをウォークスルーするiterため、を再割り当てすることはありません。iter.next()

お役に立てれば!

于 2015-08-03T21:37:42.817 に答える