如何从设置索引开始遍历 ArrayList?

问题描述:

我有一个 ArrayList,我想从索引 100 开始遍历它,直到结束.我该怎么做?

I have an ArrayList and I want to start iterating through it from, say, index 100 to the end. How do I do that?

有很多方法可以做到这一点.在这个例子中,我假设你的列表包含整数.

There are many ways to do this. In this examples I assume your list holds Integers.

  1. 你可以使用 ListIterator

  1. You can use ListIterator

ListIterator<Integer> it = list.listIterator(100);
while (it.hasNext()) {
    System.out.println(it.next());
}

或使用 for(保持迭代器在循环内的作用域)

or with for (to keep iterator scoped inside loop)

for (ListIterator<Integer> lit = list.listIterator(100); lit.hasNext();) {
    System.out.println(lit.next());
}

  • 或正常的 for 循环但从 i=100

    for (int i=100; i<list.size(); i++){
        System.out.println(list.get(i));
    }
    

  • 或者像往常一样创建 subList 并对其进行迭代

  • or just create subList and iterate over it like you normally do

    for (Integer i : list.subList(100, list.size())){
        System.out.println(i);
    }