Re: Retrieve the key from a map (2)
Chris Uppal wrote:
Robert Klemme wrote:
[me:]
It would be a lot simpler to keep a separate Map from keys to
hit-counts than to try to keep the count "in" the key.
That's an option. However, I prefer the solution I presented for the
following reasons:
- more time efficient (just a single map lookup)
- more space efficient (just one hash table)
- easier maintenance of consistency (only one map to update)
Agreed, but you don't list the downsides: more complicated code, code which
does two unrelated things with one operation, code in whch the actual values
have a somewhat obscure relationship with the logical values.
Swings and roundabouts...
and inability to reuse existing code, developed for unrelated
applications, that does one, but not both, of the jobs.
The following would need a remove method added, but it should be obvious
how to do that.
/*
* Created on Aug 14, 2004
*/
package utilities;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Utility class for counting instances of equal objects.
*/
public class Counter {
private Map<Object,Count> data = new HashMap<Object,Count>();
/**
* Increment by one the count associated with a specified
* key.
* @param key
*/
public void increment(Object key) {
Count count = data.get(key);
if (count == null) {
count = new Count();
data.put(key, count);
}
count.increment();
}
/**
* Get the count associated with a specified key.
* @param key The key whose count is required.
* @return The number of times increment has been called with
* a key equal to this one.
*/
public int get(Object key) {
Count count = data.get(key);
if (count == null) {
return 0;
} else {
return count.get();
}
}
/**
* Get number of unique counted objects
*
* @return Number of key objects for which increment
* has been called. Equal objects are only counted once.
*/
public int size() {
return data.size();
}
/**
* Get all the unique counted objects
* @return A set containing a refence to the counted objects.
*/
public Set getKeys() {
return Collections.unmodifiableSet(data.keySet());
}
private static class Count {
private int val = 0;
private void increment() {
val++;
}
private int get() {
return val;
}
}
}