Amador
Amador

Reputation: 192

How would we count the number of times the program calls the put() and get() functions?

Suppose we are using a map in our program, how would we count the number of times the program calls the put() and get() functions? . What if we created multiple instances of the map? How would you sum up the total count for each map object? Actually a friend told me that he got this question in his java job interview. I found solutions but I didn't get it clearly.

Upvotes: 2

Views: 1372

Answers (2)

EJK
EJK

Reputation: 12527

Here's one approach, assuming that it is okay for the program to use a subclass of Map rather than a standard Java Map:

public class MyMap<K, V> extends Map<K, V> {
    int getCount = 0;

     @override
     public V get(K key) {
          getCount++;
          return super.get(key);
     }

     public getGetCount() {
         return getCount;
     }
}

It is also worth noting that mocking frameworks solve a similar problem (although this particular problem is just one small thing that they do). Mockito for example produces mock versions of classes/interfaces that count the number of invocations of each method. The mocks themselves are not immediately usable unless you implement some stubbing behaviors. Or if you use a mockito, spy, that is similar to inheritance and might be the fastest way to achieve this behavior. See https://code.google.com/p/mockito/ for more info.

Upvotes: 1

Christian Tapia
Christian Tapia

Reputation: 34146

If you just want to add the calls to methods in a class, use an static field:

public class Map ... {
    private static int count = 0;

    public ... get(...) {
        count++;
        ...
    }

    public void put(...) {
        count++;
        ...
    }

    public static int getCount() {
        return count;
    }
}

Upvotes: 2

Related Questions