using two iterators in one ArrayList

后端 未结 5 1291
遇见更好的自我
遇见更好的自我 2021-01-19 09:16

Edit: Thank you for all your prompt replies. Now I see the assignment won\'t work. From another thread I read that iterator in Java is much less powerful than iterator in C+

相关标签:
5条回答
  • 2021-01-19 09:29

    Since you seem to be using lists, the simplest solution in your case is to use two indexes, something like this:

    for (int i = 0; i < aList.size(); i++) {
      for (int j = i; j < aList.size(); j++) {
        // do stuff with aList's elements
        aList.get(j);
      }
    }
    

    With iterators, you can achieve similar things, but you have to construct new iterators for the inner loop, possibly from

    aList.subList(i, aList.size()).iterator();
    
    0 讨论(0)
  • 2021-01-19 09:31

    Do this:

    ArrayList<String> aList = new ArrayList<String>();
    // do something to fill the list
    for (int i = 0; i < aList.size(); i++)
    {
      ArrayList<String> bList = aList.subList(i, aList.size());
      for (int j = 0; j < bList.size(); j++)
      {
        // do stuff with the sublist
      }
    }
    

    It's important to note that bList is backed by aList so changes to bList will be reflected in aList...make non-structural changes only to keep your sanity.

    0 讨论(0)
  • 2021-01-19 09:33

    You shouldn't do:

    Iterator bIter = aIter;
    

    Because there is no copy constructor etc in Java; bIter will be a reference to the same underlying iterator.

    You could use a ListIterator this way:

    ListIterator aItr = aList.listIterator();
    while (aItr.hasNext()) {
     int a = aItr.next();
     ListIterator bItr = aList.listIterator(aItr.previousIndex());
     while (bItr.hasNext()) {
       // ...
     }
    }
    

    But If you are thinking that ListIterator should have had a copy() method or something along those lines, I agree with you...

    0 讨论(0)
  • 2021-01-19 09:33

    If you want a second list iterator at position n in the list then use List#listIterator(int index):

    ListIterator bIter = list.listIterator(n);
    
    0 讨论(0)
  • 2021-01-19 09:54

    It's valid, but it won't do what you want it to do. You'll still have only one iterator, and the outer loop will terminate after the inner one has terminated for the first time.

    Java iterators cannot be copied meaningfully. You'll have to use a simple for loop that increments indexes.

    0 讨论(0)
提交回复
热议问题