3 ms·
This is a key failing of Java, but you can make it hurt a little less with syntax like: Map<String,Integer> map = new HashMap<String,Integer>() {{
by jimbokun 18y ago
This is a key failing of Java, but you can make it hurt a little less with syntax like:
Map<String,Integer> map = new HashMap<String,Integer>() {{
put("x", 1);
put("y", 2);
}}
This abuses the fact that a brace after a constructor invocation indicates the creation of an anonymous inner subclass, and the second brace indicates code to be executed at instantiation time. So this "double brace initialization" has become a Java idiom. Still pretty awful, I know.
I'm not sure if anyone has been able to use generics and varargs to create a map generating static function, but it might be possible. Something like:
Map<String,Object> m = map("x", 1, "y", 2);
I think the trouble is with automatically extracting the key value types from the varargs array. I think I have seen the approach:
Map<String,Object> m = map(kv("x", 1), kv("y", 2));
where kv would just create a key value pair. That way you can make the generics inference come out right.
All of this does make a pretty good argument for Python, Ruby, Javascript, etc.
UPDATE: just found this:
http://nicolas.lehuen.com/index.php/post/2006/10/07/113-java-map-literals-continued http://nicolas.lehuen.com/index.php/post/2006/10/07/113-java...
// Example usage :
import static Literals.map;
Map<String,Integer> example = map("hello",1).map("world",2).map("!",3);
Pick your poison.
- michaelneale 18y agoCheck out: http://gleichmann.wordpress.com/2008/01/13/building-your-own-literals-in-java-lists-and-arrays/ http://gleichmann.wordpress.com/2008/01/13/building-your-own... for more tricks with varargs, generics and static imports to "pimp" things up a bit.