Java creating instance of a map object Java creating instance of a map object arrays arrays

Java creating instance of a map object


Map is an interface. Create an instance of one the classes that implements it:

Map<String, String> temp = new HashMap<String, String>();temp.put(colName, data);

Or, in Java 7:

Map<String, String> temp = new HashMap<>();temp.put(colName, data);


@JohnGirata is correct.

If you're REALLY upset, you could have a look here http://nileshbansal.blogspot.com.au/2009/04/initializing-java-maps-inline.html

It's not quite what you're asking, but is a neat trick/hack non the less.


The quick way of putting entries in a Map just created is the following (let me use a HashMap 'cause I like them):

Map<String,String> temp = new HashMap<String,String>(){{    put(colName, data);}};

Note all those parenthesis with a closing semicolon!

While it's true that in Java7 you can generally use the diamond operator and write something like this Map<String,String> temp = new HashMap<String,String>();, this does not work when putting elements in the Map inline. In other words, the compiler with yell at you if you try the following (don't ask me why):

Map<String,String> temp = new HashMap<>(){{    put(colName, data);}};