Best Loop Idiom for special casing the last element

后端 未结 18 985
梦毁少年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 09:58

    I think it is easier to think of the first element as the special case because it is much easier to know if an iteration is the first rather than the last. It does not take any complex or expensive logic to know if something is being done for the first time.

    public static String prettyPrint(String[] items) {
        String itemOutput = "[";
        boolean first = true;
    
        for (int i = 0; i < items.length; i++) {
            if (!first) {
                itemOutput += ", ";
            }
    
            itemOutput += items[i];
            first = false;
        }
    
        itemOutput += "]";
        return itemOutput;
    }
    

提交回复
热议问题