Double braces initialization in Java

This little trick is not very well known and can look like completely new syntax to the uninitiated.

But it is actually a form of something you use quite frequently – anonymous inner classes.

		
		// Normal list initialization
		List<String> days1 = new ArrayList<String>();
		days1.add("Sun");
		days1.add("Mon");
		days1.add("Tue");

		// Double braces initialization. Compact!
		List<String> days2 = new ArrayList<String>() {{
			add("Sun");
			add("Mon");
			add("Tue");
		}};

My suggestion is to NOT use it because it can cause serialization warnings and is just too unfamiliar for most Java developers. When in doubt, favour clarity!



Tags:
This entry was posted on Sunday, January 8th, 2012 at 7:12 pm and is filed under Uncategorized. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

One Response to “Double braces initialization in Java”

  1. madhava sridhar

    Arrays.asList(
    “Sun”,
    “Mon”,
    “Tue”
    )

    is compact still clear