Best Loop Idiom for special casing the last element

后端 未结 18 982
梦毁少年i
梦毁少年i 2020-12-23 09:25

I run into this case a lot of times when doing simple text processing and print statements where I am looping over a collection and I want to special case the last element (

18条回答
  •  半阙折子戏
    2020-12-23 10:17

    I'd go with your second example, ie. handle the special case outside of the loop, just write it a bit more straightforward:

    String itemOutput = "[";
    
    if (items.length > 0) {
        itemOutput += items[0];
    
        for (int i = 1; i < items.length; i++) {
            itemOutput += ", " + items[i];
        }
    }
    
    itemOutput += "]";
    

提交回复
热议问题