Best Loop Idiom for special casing the last element

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

    If you are just looking for a comma seperated list of like this: "[The, Cat, in, the, Hat]", don't even waste time writing your own method. Just use List.toString:

    List strings = Arrays.asList("The", "Cat", "in", "the", "Hat);
    
    System.out.println(strings.toString());
    

    Provided the generic type of the List has a toString with the value you want to display, just call List.toString:

    public class Dog {
        private String name;
    
        public Dog(String name){
             this.name = name;
        }
    
        public String toString(){
            return name;
        }
    }
    

    Then you can do:

    List dogs = Arrays.asList(new Dog("Frank"), new Dog("Hal"));
    System.out.println(dogs);
    

    And you'll get: [Frank, Hal]

提交回复
热议问题