8

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

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

Where colName, data are string variables.

Thanks.

1
  • 1
    Even though it's not available now, I believe this will land in Java 8 unless they dropped it when I wasn't paying attention. Commented Jul 30, 2012 at 1:40

3 Answers 3

16

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);
Sign up to request clarification or add additional context in comments.

2 Comments

can you explain why in java7 is that possible?
In Java 7, support was added for omitting the types in certain cases. It's just to make the code a little cleaner.
3

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.