C# refugee seeks a bit of Java collections help

collections, dictionary, java

Solution

You want to use a `Map`

Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Stop me", 11);
Integer i = m.get("Stop me"); // i == 11

Note that on the last line, I could have said:

int i = m.get("Stop me");

Which is shorthand for (with Java's auto-unboxing):

int i = m.get("Stop me").intValue()

If there is no value in the map at the given key, the `get` returns `null` and this expression throws a `NullPointerException`. Hence it's always a good idea to use the boxed type `Integer` in this case

Problem

I need to store key/value info in some type of collection. In C#, I'd define a dictionary like this: ``` var entries = new Dictionary<string, int>(); entries.Add("Stop me", 11); entries.Add("Feed me", 12); entries.Add("Walk me", 13); ``` Then I would access the values so: ``` int value = entries["Stop me"]; ``` How do I do this in Java? I've seen examples with `ArrayList`, but I'd like the solution with generics, if possible.

Original source