[java] Iterator를 사용할 때 현재 루프 인덱스를 얻는 방법은 무엇입니까?

Iterator를 사용하여 컬렉션을 반복하고 현재 요소의 인덱스를 가져오고 싶습니다.

어떻게 할 수 있습니까?



답변

자신의 변수를 사용하고 루프에서 증가시킵니다.


답변

나는 같은 질문이 있었고 ListIterator를 사용하여 효과가 있음을 알았습니다. 위의 테스트와 유사합니다.

List<String> list = Arrays.asList("zero", "one", "two");

ListIterator iter = list.listIterator();

while (iter.hasNext()) {
    System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}

실제로 next ()를 얻기 전에 nextIndex를 호출했는지 확인하십시오.


답변

자체 변수를 사용하고 간결하게 유지하는 방법은 다음과 같습니다.

List<String> list = Arrays.asList("zero", "one", "two");

int i = 0;
for (Iterator<String> it = list.iterator(); it.hasNext(); i++) {
    String s = it.next();
    System.out.println(i + ": " + s);
}

출력 (당신이 추측) :

0: zero
1: one
2: two

장점은 루프 내에서 인덱스를 증가시키지 않는다는 것입니다 (반복 당 한 번만 Iterator # next를 호출하도록주의해야하지만 맨 위에서 만 수행).


답변

ListIterator계산을 수행하는 데 사용할 수 있습니다 .

final List<String> list = Arrays.asList("zero", "one", "two", "three");

for (final ListIterator<String> it = list.listIterator(); it.hasNext();) {
    final String s = it.next();
    System.out.println(it.previousIndex() + ": " + s);
}


답변

어떤 종류의 컬렉션? List 인터페이스의 구현 인 경우 it.nextIndex() - 1.


답변

용도 반복자 컬렉션을 반복합니다. 컬렉션이 목록이 아닌 경우 Arrays.asList(Collection.toArray())먼저 목록으로 전환하는 데 사용 합니다.


답변

다음과 같이하십시오.

        ListIterator<String> it = list1.listIterator();
        int index = -1;
        while (it.hasNext()) {
            index++;
            String value = it.next();
            //At this point the index can be checked for the current element.

        }