Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java creating instance of a map object

Really simple question hopefully. I want to do something like this:

Map<String, String> temp = { colName, data };

Where colName, data are string variables.

Thanks.

like image 575
JDS Avatar asked Jul 30 '12 01:07

JDS


People also ask

How do you initialize a map in Java?

The Static Initializer for a Static HashMap We can also initialize the map using the double-brace syntax: Map<String, String> doubleBraceMap = new HashMap<String, String>() {{ put("key1", "value1"); put("key2", "value2"); }};

What does map () do in Java?

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.


2 Answers

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);
like image 72
John Girata Avatar answered Oct 05 '22 23:10

John Girata


@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.

like image 43
MadProgrammer Avatar answered Oct 06 '22 00:10

MadProgrammer