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>();

    LIST2 = new ArrayList<String>();

an alternative way to write it is this:

public static final List<String> LIST1 = new ArrayList<String>  {{

public static final List<String> LIST2 = new ArrayList<String>  {{

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

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