Reputation: 16015
In my C# project I have a static List that gets filled immediately when declared.
private static List<String> inputs = new List<String>()
{ "Foo", "Bar", "Foo2", "Bar2"};
How would I do this in Java using the ArrayList?
I need to be able to access the values without creating a instance of the class. Is it possible?
Upvotes: 2
Views: 12700
Reputation: 11733
You can make static calls by enclosing them within static{} brackets like such:
private static final List<String> inputs = new ArrayList<String>();
static {
inputs.add("Foo");
inputs.add("Bar");
inputs.add("Foo2");
inputs.add("Bar2");
}
Upvotes: 7
Reputation: 40851
You may enjoy ImmutableList
from Guava:
ImmutableList<String> inputs = ImmutableList.of("Foo", "Bar", "Foo2", "Bar2");
The first half of this youtube video discusses the immutable collections in great detail.
Upvotes: 3
Reputation: 9058
You can use Double Brace Initialization. It looks like:
private static List<String> inputs = new ArrayList<String>()
{{ add("Foo");
add("Bar");
add("Foo2");
add("Bar2");
}};
Upvotes: 16
Reputation: 26586
I don't understand what you mean by
able to access the values without creating a instance of the class
but the following snippet of code in Java has pretty much the same effect in Java as yours:
private static List<String> inputs = Arrays.asList("Foo", "Bar", "Foo2", "Bar2");
Upvotes: 8
Reputation: 11162
Do you need this to be an ArrayList
specifically, or just a list?
Former:
private static java.util.List<String> inputs = new java.util.ArrayList<String>(
java.util.Arrays.<String>asList("Foo", "Bar", "Foo2", "Bar2"));
Latter:
private static java.util.List<String> inputs =
java.util.Arrays.<String>asList("Foo", "Bar", "Foo2", "Bar2");
java.util.Arrays#asList(...) API
Upvotes: 5