How can I initialize a collection and add data on the same line?

This question already has an answer here:

  • Initialization of an ArrayList in one line 32 answers

  • If you need a read-only List

    List<String> numbers = Arrays.asList("one","two","three");
    
    // Can't add since the list is immutable
    numbers.add("four"); // java.lang.UnsupportedOperationException
    

    If you would like to modify the List later on.

    List<String> numbers2 = new ArrayList<String>(
                                Arrays.asList("one","two","three"));
    numbers2.add("four");
    
    System.out.println(numbers2); // [one, two, three, four]
    

    I prefer doing this using the Guava (formerly called Google Collections) library, which both removes the need to write the type down again AND has all kinds of ways of adding data straight away.

    Example: List<YourClass> yourList = Lists.newArrayList();

    Or with adding data: List<YourClass> yourList = Lists.newArrayList(yourClass1, yourclass2);

    The same works for all other kinds of collections and their various implementations. Another example: Set<String> treeSet = Sets.newTreeSet();

    You can find it at https://code.google.com/p/guava-libraries/


    You can use Arrays.asList(T... a)

    List<String> foo = Arrays.asList("one","two","three");
    

    As Boris mentions in the comments the resulting List is immutable (ie. read-only). You will need to convert it to an ArrayList or similar in order to modify the collection:

    List<String> foo = new ArrayList<String>(Arrays.asList("one","two","three"));
    

    You can also create the List using an anonymous subclass and initializer:

    List<String> foo = new ArrayList<String>() {
        {
            add("one");
            add("two");
            add("three");
        }
    };
    
    链接地址: http://www.djcxy.com/p/27708.html

    上一篇: 将多个BigInteger值添加到ArrayList

    下一篇: 我如何初始化一个集合并在同一行添加数据?