Complex static initializing in Java

Sometimes you need to set up static complex structures in Java with data that you have right away, for testing purposes, for instance. Doing this in dynamic languages is quite straightforward most of the time, but in Java the syntax does not help a lot. Check this out, the initialization of an static array of string to string maps:

private static final Map<String, String>[] HEADERS;

 static {
 HEADERS = new Map[] { new HashMap<String, String>() {
 {
 put("x", "y");
 }
 }, new HashMap<String, String>() {
 {
 put("x", "y");
 }
 }, new HashMap<String, String>() {
 {
 put("x", "y");
 }
 }, };

 }

This works, although it looks ugly, and it is a bit difficult to read. And I could not found a way to get rid of the warning about an unchecked conversion because of the missing generic parameters to the Map[] initialization…

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión / Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión / Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión / Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión / Cambiar )

Conectando a %s