Identifying last loop when using for each

后端 未结 25 1488
眼角桃花
眼角桃花 2020-12-08 09:59

I want to do something different with the last loop iteration when performing \'foreach\' on an object. I\'m using Ruby but the same goes for C#, Java etc.

          


        
25条回答
  •  情书的邮戳
    2020-12-08 10:15

    I don't know how for-each loops works in other languages but java. In java for-each uses the Iterable interface that is used by the for-each to get an Iterator and loop with it. Iterator has a method hasNext that you could use if you could see the iterator within the loop. You can actually do the trick by enclosing an already obtained Iterator in an Iterable object so the for loop got what it needs and you can get a hasNext method inside the loop.

    List list = ...
    
    final Iterator it = list.iterator();
    Iterable itw = new Iterable(){
      public Iterator iterator () {
        return it;
      }
    }
    
    for (X x: itw) {
      doSomething(x);
      if (!it.hasNext()) {
        doSomethingElse(x);
      }
    }
    

    You can create a class that wraps all this iterable and iterator stuff so the code looks like this:

    IterableIterator itt = new IterableIterator(list);
    for (X x: itit) {
      doSomething(x);
      if (!itit.hasNext()) {
        doSomethingElse(x);
      }
    }
    

提交回复
热议问题