Question

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.

Was it helpful?

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

OTHER TIPS

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.

You use a Map in Java.

Note that you can't use int (or any other primitive type) as a generic type parameter, but because of autoboxing, it still behaves almost as if it were a Map<String, int> instead of a Map<String, Integer>. (You don't want to be doing a lot of autoboxing in performance-sensitive code, though.)

Map<String, Integer> entries = new HashMap<String, Integer>();
entries.put("Stop me", 11);
entries.put("Feed me", 12);
entries.put("Walk me", 13);
int value = entries.get("Stop me"); // if you know it exists
// If you're not sure whether the map contains a value, it's better to do:
Integer boxedValue = entries.get("Punch me");
if (boxedValue != null) {
    int unboxedValue = boxedValue;
    ...
}

It looks like you are looking for something like HashMap

Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Stop Me", 11);
map.put("Feed Me", 12);
map.put("Walk Me", 13);
Integer x; // little hack
int value = (x = a.get("aaa")) == null? 0 : x;

as alternative you can try Enum:

enum Action {

    STOP(11),
    FEED(12),
    WALK(13);

    private final int value;

    private Action(int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

    public static Action valueOf(int value) {
        for (Action action : values()) {
            if (action.value == value) {
                return action;
            }
        }

        return null; // or a null-object
    }
}

test:

public void action() {
    Action action = Action.valueOf("FEED"); 
    // or Action.FEED for more compile-time safety
    int value = action.value();
    // instantiating by code 
    Action walk = Action.valueOf(13);
}

You definitely want a HashMap, which is the Java version of C# Dictionary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top