Inline Construction of Static Lists (and other classes)

2011-03-03

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

1
2
3
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:

1
2
3
4
5
6
7
8
9
public static final List LIST1;
public static final List LIST2;
{
LIST1 = new ArrayList();
LIST1.add("value1");
LIST2 = new ArrayList();
LIST2.addAll(LIST1);
LIST2.add("value2");
}

an alternative way to write it is this:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
8
9
public static final List<String> LIST2 = new ArrayList<String> {
private Long someField;
public Long getSomeField() { return someField; }
///code appears here
{
addAll(LIST1);
add("version2");
}
}

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


Comments: