Compact syntax for instantiating an initializing collection

前端 未结 6 1209
长发绾君心
长发绾君心 2021-01-01 11:57

I\'m looking for a compact syntax for instantiating a collection and adding a few items to it. I currently use this syntax:

Collection collecti         


        
6条回答
  •  悲&欢浪女
    2021-01-01 12:46

    I guess you're thinking about

    collection = new ArrayList() { // anonymous subclass
         { // anonymous initializer
             add("1");
             add("2");
             add("3");
         }
    }
    

    which, one comapcted, gives

    collection = new ArrayList() {{ add("1"); add("2"); add("3"); }}
    

    FUGLY, to say the least. However, there is a variant to the Arrays.asList method : Arrays.asList(T...a) which provides comapcity and readability. As an example, it gives the following line of code :

    collection = new ArrayList(Arrays.asList("1", "2", "3")); // yep, this one is the shorter
    

    And notice you don't create an anonymous subclass of ArrayList of dubious use.

提交回复
热议问题