The T-Files


Sat, 17 Jan 2009

The thousand and one things I want to see fixed in Java: [2] Collection and other literals

Tieing in with the second of my almost thousand and one reasons to love Perl, the Java language really needs a few more straightforward ways to create objects from values given in program source code.

No problem with (single-line) strings and arrays:

String x = "abc";

int[] a = new int[] { 1, 2, 3, 4, 5 };

Lists can be created using array literals (or varargs):

List<String> ls = Arrays.asList("a", "b", "c");

No such luck with Maps. Some people suggest to use an instance initializer block, but this actually creates an anonymous inner class, which seems costly and can have unexpected side-effects.

new HashMap() {{
	put("a", "first");
	put("b", "second");
	put("c", "third");
}};

But worst of all are regular expressions, because they need to be constructed from Strings, and they frequently use backslashes, which unfortunately act as character escapes in String literals so that you have to double all of them. If you thought regular expressions where hard to read in the first place, wait until you see them in Java:

Pattern emailRegEx = 
    Pattern.compile("(\\w+)@(\\w+\\.)(\\w+)(\\.\\w+)*");