If I want an empty map or a one element map, Java Collections has a method for that. Why is there no method for more than one element? What’s the best way to create a static final map with 2 elements in it? I know I can do something like:
private static final Map<String, String> MAP = new HashMap<String, String>() {
{ put("a", "b"); put("c", "d"); }
};
But then Eclipse complains about the serialVersionUID…
The reason
Collectionshas methods for 0 and 1 entry maps is because they are special cases… the emptyMapis an immutable singleton for example.For what you want to do, though, I’d strongly recommend using Guava. Its
Immutable*collections (ImmutableMapspecifically) are what you want I think:You can do the above for small maps, and for bigger maps you can write:
If you don’t use Guava, you’ll still likely want to ensure that this map can’t be changed. This is a lot uglier: