Monday, August 10, 2015

Defining Map to maintain counter on key basis


Most of the time if we have to maintain a counter on key basis then we define a map as follows
Map<String, Integer> map = new HashMap<String, Integer>();
Do we have any problem with the above statement???
Yes, the problem is with value but what's the problem with Integer as a value?
We have defined Integer object as a value and Integer is an immutable class so whenever we perform operation on the value (increment or decrement) a new Integer object will be created this is where the problem lines in, after increment/decrement n number of time we might have created n number of objects.
So whats the solution for the above problem
1) A very simple solution is to define a bean and take primitive int/long/double (whatever datatype you want) and based on the key increment/decrement the values in the bean object and provide getters to get the Count.
2) We can use AtomicInteger because its mutable.
Keep exploring Java smile emoticon

No comments:

Post a Comment