How to 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?

My initial thoughts(code):

public class MyMap<K, V> extends HashMap<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;

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: