Saturday, April 5, 2014

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

Problem

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?

Solution

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;
 
    @Override
    public V put(K key, V value) {
        putCount++;
        return super.put(key, value);
    }
 
    @Override
    public V get(Object key) {
        getCount++;
        return super.get(key);
    }
 
    public int getPutCount() {
        return putCount;
    }
 
    public int getGetCount() {
        return getCount;
    }
}

References
http://tianrunhe.wordpress.com/2012/04/15/how-to-count-the-number-of-calls-of-put-and-get-for-a-map-in-java/
http://stackoverflow.com/questions/20027078/how-would-we-count-the-number-of-times-the-program-calls-the-put-and-get-fun 

0 comments:

Post a Comment