Inline construction of static Lists (and other classes)

I’m sure you’ve seen this form of initialization many times

public static final String[] SOME_ARRAY = new String[] { "value1", "value2"};

but what if you want to have lists? or you want to have a list that builds upon another list?

Then odds are this is what you’ve written:

public static final List<String> LIST1;
public static final List<String> LIST2;

static {
    LIST1 = new ArrayList<String>();
    LIST1.add("value1");

    LIST2 = new ArrayList<String>();
    LIST2.addAll(LIST1);
    LIST2.add("value2");
}

an alternative way to write it is this:

public static final List<String> LIST1 = new ArrayList<String>  {{
    add("value1");
}}

public static final List<String> LIST2 = new ArrayList<String>  {{
    addAll(LIST1);
    add("value2");
}}

Personally, I think the above is cleaner, and easier to follow, so if you agree, consider using it the next time you want this type of construct.

To explain what’s happening here, basically, you are constructing an anonymous subclass of ArrayList, and whatever is inside the nested {} is the constructor.

You could, although I wouldn’t recommend it, do something like this:

public static final List<String> LIST2 = new ArrayList<String>  {
    private Long someField;
    public Long getSomeField() { return someField; }
 ...
{
    addAll(LIST1);
    add("value2");
}}

One place where this syntax is put to use is JMock2 and construction of it’s expectations.

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply