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 一次——只需要在顶部调用)。
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);
}
public static void main(String[] args) {
String[] str1 = {"list item 1", "list item 2", "list item 3", "list item 4"};
List<String> list1 = new ArrayList<String>(Arrays.asList(str1));
ListIterator<String> it = list1.listIterator();
int x = 0;
//The iterator.nextIndex() will return the index for you.
while(it.hasNext()){
int i = it.nextIndex();
System.out.println(it.next() + " is at index" + i);
}
}
这段代码将一次遍历 list1列表中的一个项目并打印该项目的文本,然后“ is at index”,然后它将打印迭代器找到的索引。:)
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.
}
Has no iterators, but can be iterated using through the keySet() / values() or entrySet() as keySet() and entrySet() returns Set and values() returns Collection.