Saturday, April 5, 2014

Count the number of calls of put() and get() for a map in Java


Suppose you are using a map in your program, how would you count the number of times the program calls the put() and get() functions?


Method 1 -  Implement the map interface with static count field
One simple solution is to put count variables for get() and put() methods and, whenever they are called, increment the count. We can also achieve this by extending the existing library map and overriding the get() and put() functions.
At first glance, this seems to work. However, what if we created multiple instances of the map? How would you sum up the total count for each map object?
The simplest solution for this is to keep the count variables static. We know static variables have only one copy for all objects of the class so the total count would be reflected in count variables.
public class MyMap<K, V> extends Map<K, V> {
    private static int putCount = 0;
    private static int getCount = 0;
    public V put(K key, V value) {
        return super.put(key, value);
    public V get(Object key) {
        return super.get(key);
    public int getPutCount() {
        return putCount;
    public int getGetCount() {
        return getCount;



Post a Comment