Best Loop Idiom for special casing the last element

后端 未结 18 1017
梦毁少年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:08

    If you are building a string dynamically like that, you shouldn't be using the += operator. The StringBuilder class works much better for repeated dynamic string concatenation.

    public String commaSeparate(String[] items, String delim){
        StringBuilder bob = new StringBuilder();
        for(int i=0;i

    Then call is like this

    String[] items = {"one","two","three"};
    StringBuilder bob = new StringBuilder();
    bob.append("[");
    bob.append(commaSeperate(items,","));
    bob.append("]");
    System.out.print(bob.toString());
    

提交回复
热议问题