7
package wrap;
import java.util.*;
public class ArrayListDemo {

    public static void main(String [] args){
        ArrayList<String> a=new ArrayList<String>();
        a.add("B");
        a.add("C");
        a.add("D");
        ListIterator<String> i=a.listIterator();
        while(i.hasPrevious()){
            System.out.println(i.previous());
        }
    }

}

このプログラムは、hasNext() および next() メソッドに対しては正常に動作しますが、hasPrevious() および previous() に対しては、次のようなメッセージが表示されます。

<terminated> ArrayListDemo [Java Application] C:\Program Files (x86)\Java\jre7\bin\javaw.exe (28-Oct-2013 3:20:35 PM)
4

6 に答える 6

18

ドキュメントから:

public ListIterator<E> listIterator()

このリスト内の要素に対するリスト反復子を (適切な順序で) 返します。

boolean hasPrevious()

リストを逆方向にトラバースするときに、このリスト反復子にさらに要素がある場合は true を返します。

イテレータが最初の位置にあるため、hasPrevious()false が返され、while ループは実行されません。

 a's elements

    "B"  "C"  "D"
     ^
     |

Iterator is in first position so there is no previous element

もしあなたがそうするなら :

    ListIterator<String> i=a.listIterator(); <- in first position
    i.next(); <- move the iterator to the second position
    while(i.hasPrevious()){
        System.out.println(i.previous());
    }

次の状況にあるため、印刷さ"B"れます。


aの要素

        "B"  "C"  "D"
              ^
              |
    Iterator is in second position so the previous element is "B"

メソッドを使用することもできますlistIterator(int index)。で定義された位置に反復子を配置できますindex

もしあなたがそうするなら :

ListIterator<String> i=a.listIterator(a.size());

印刷します

D
C
B
于 2013-10-28T09:57:34.217 に答える
3

Since you get the default ListIterator for the list, it starts with the first element, which is why hasPrevious() returns false and the while loop is exited. If you want to traverse the list in the reverse order, get the ListIterator from the last index and traverse backwards using the hasPrevious() and previous() methods.

ListIterator<String> i = a.listIterator(a.size()); // Get the list iterator from the last index
while (i.hasPrevious()) {
    System.out.println(i.previous());
}
于 2013-10-28T10:01:00.713 に答える
2
ListIterator<String> i=a.listIterator();

最初に私が指すイテレータindex of 0

あなたはindex 0そうで、前の要素はありません。

于 2013-10-28T09:58:27.887 に答える
0

他の人が言ったように、あなたのポインターはまだリストの最初の要素を指しているので、-1 は不可能です。

サイズ n のリストには、インデックスとして 1,2 ....n-1 が含まれます。

n-1 は -1 ではありません。

これが hasPrevious と previous が機能しない理由です。

乾杯。

于 2019-09-23T11:44:39.460 に答える
0

リストの先頭から開始されるため、そのポイントより前には何もありません。これらの方法を使用する場合は、ListIterator.

ドキュメント.

于 2013-10-28T09:57:33.447 に答える
0

リストの最後またはその間のどこかに到達して戻ってきました。インデックス 0 の要素の前の要素はありません。

例えば

System.out.println("Elements in forward directiton");
        while(i.hasNext()){
            System.out.println(i.next());
        }
System.out.println("Elements in backward directiton");
        while(i.hasPrevious()){
            System.out.println(i.previous());
        }
于 2013-10-28T09:59:15.397 に答える