How to start iterating through ArrayList from set index? [closed]

▼魔方 西西 提交于 2019-12-20 07:39:23

问题


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


回答1:


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

  1. You can use ListIterator

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

    or with for (to keep iterator scoped inside loop)

    for (ListIterator<Integer> lit = list.listIterator(100); lit.hasNext();) {
        System.out.println(lit.next());
    }
    
  2. or normal for loop but start from i=100

    for (int i=100; i<list.size(); i++){
        System.out.println(list.get(i));
    }
    
  3. or just create subList and iterate over it like you normally do

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



回答2:


You can always utilize the subList(int, int) method

list.subList(100,list.size()).iterator();



回答3:


Try like this to iterate over a range:

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



回答4:


Use a ListIterator. And read the API documentation, thank you.

ListIterator<YourType> iter = list.listIterator(start);



回答5:


Use ListIterator

ListIterator<Type> iter = list.listIterator(start);


来源:https://stackoverflow.com/questions/20140744/how-to-start-iterating-through-arraylist-from-set-index

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!