Identifying last loop when using for each

后端 未结 25 1501
眼角桃花
眼角桃花 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:04

    What you are trying to do seems just a little too advanced for the foreach-loop. However, you can use Iterators explicitly. For example, in Java, I would write this:

    Collection ss = Arrays.asList("A","B","C");
    Iterator it = ss.iterator();
    while (it.hasNext()) {
        String s = it.next();
        if(it.hasNext())
            System.out.println("Looping: " + s);
        else 
            System.out.println("Last one: " + s);
    }
    

提交回复
热议问题