JDS
JDS

Reputation: 16978

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.

Upvotes: 8

Views: 45750

Answers (3)

Marsellus Wallace
Marsellus Wallace

Reputation: 18601

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);
}};

Upvotes: 3

John Girata
John Girata

Reputation: 2091

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);

Upvotes: 16

MadProgrammer
MadProgrammer

Reputation: 347194

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

Upvotes: 3

Related Questions