Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

People also ask

Can you instantiate a collection?

The Java Collection interface ( java. util. Collection ) is one of the root interfaces of the Java Collection API. Though you do not instantiate a Collection directly, but rather a subtype of Collection, you may often treat these subtypes uniformly as a Collection.


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]

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");
    }
};

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/


The best that I've been able to come up with is:

final List<String> foo = new ArrayList<String>() {{
  add("one");
  add("two");
  add("three");
}};

Basically, that says that you are creating an anonymous sub-class of the ArrayList class which is then statically initialized using "one", "two", "three".