Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# refugee seeks a bit of Java collections help

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.

like image 849
AngryHacker Avatar asked Jun 22 '09 20:06

AngryHacker


2 Answers

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

like image 101
oxbow_lakes Avatar answered Sep 21 '22 00:09

oxbow_lakes


Use a java.util.Map. There are several implementations:

  • HashMap: O(1) lookup, does not maintain order of keys
  • TreeMap: O(log n) lookup, maintains order of keys, so you can iterate over them in a guaranteed order
  • LinkedHashMap: O(1) lookup, iterates over keys in the order they were added to the map.

You use them like:

Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Stop me", 11);
map.put("Feed me", 12);

int value = map.get("Stop me");

For added convenience working with collections, have a look at the Google Collections library. It's excellent.

like image 25
Nat Avatar answered Sep 21 '22 00:09

Nat