views:

522

answers:

5

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?

+3  A: 

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

jdmichal
+2  A: 

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");
MAK
As it is a static field, it really should be immutable. Unfortunately this adds to the verbosity. `private static final List<String> inputs = Collections.unmodifiableList(Arrays.asList("Foo", "Bar", "Foo2", "Bar2"));`. Should get list literals in JDK7.
Tom Hawtin - tackline
Yay for the less verbose, later answer winning out? (No offense to you MAK. Just stating my perceived truth.)
jdmichal
@jdmichal: I think your answer was posted while I was still writing mine - otherwise I wouldn't have bothered to say the same thing again. I guess the slowest gun won :).
MAK
+3  A: 

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");
  }};
Clint
+1 for an interesting technique I've never seen before!
jdmichal
IMO This is the best answer, since it doesn't rely on helper class java.util.Arrays.
Adriaan Koster
But it does create a somewhat hidden anonymous inner class. Subjective call on whether or not that is a better tradeoff.
jdmichal
+2  A: 

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.

Kevin Bourrillion
+1  A: 

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");
}
Jason Nichols
That's nice, I didn't know that.
Peterdk