Initialization of an ArrayList in one line

后端 未结 30 2692
北恋
北恋 2020-11-22 01:10

I wanted to create a list of options for testing purposes. At first, I did this:

ArrayList places = new ArrayList();
places.add(\         


        
30条回答
  •  不要未来只要你来
    2020-11-22 01:56

    With Eclipse Collections you can write the following:

    List list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    

    You can also be more specific about the types and whether they are Mutable or Immutable.

    MutableList mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    ImmutableList iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");
    

    You can also do the same with Sets and Bags:

    Set set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    MutableSet mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    ImmutableSet iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");
    
    Bag bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    MutableBag mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
    ImmutableBag iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题