In C# I can create a collection of some kind and initialize it with data on the same line.
var foo = new List<string> {"one","two","three"};
Is there an equivalent way to do this in Java?
In C# I can create a collection of some kind and initialize it with data on the same line.
var foo = new List<string> {"one","two","three"};
Is there an equivalent way to do this in Java?
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"
.
List<String> list = Arrays.asList("one","two","three")
List<String> numbers = Arrays.asList("one","two","three");
As Boris commented, it makes your numbers
immutable.
Yes,You can, but with two lines.
List<String> numbers= new ArrayList<String>();
Collections.addAll(numbers,"one","two","three");
If you still want in Only in one line ,With Gauva
List<String> numbers= Lists.newArrayList("one","two","three");