I want to extend HashMap
to add the method putIfGreaterThan
which basically retrieves the value for a given key and if the new value is greater than the old value we update the old value with the new value. Like this:
public void putIfGreaterThan(String key, Double value )
{
if (containsKey(key ) != true) {
put( key , value );
} else {
if (get(key ) < value) {
System. out .println("Adding new value: " + value + " to map" );
put( key , value );
} else {
System. out .println("Did not add value: " + value + " to map" );
}
}
}
The program above works fine - however I would like to add this method to both HashMap
and LinkedHashMap
. In other words, if someone instantiates:
HashMap hashmap = new HashMap();
They should be able to access the method:
hashmap.putIfGreaterThan();
And if someone instantiates:
LinkedHashMap linkedhashmap = new LinkedHashMap();
They should be able to access the method:
linkedhashmap .putIfGreaterThan();
If I create a new class as follows:
MyHashMap extends HashMap<String, Double>
and add the previously mentioned method - I am only extending HashMap
not LinkedHashMap
. This would not allow me to access the method if I instantiate a LinkedHashMap
.
I was thinking of modifying the source code in the original HashMap class (by adding the method putIfGreaterThan
) however I am unable to modify the source code unless I de-compile the entire class (and when I try doing this I get a bunch of other errors so I figured it would be easier just to extend the HashMap
class but doing this means I cannot use the method putIfGreaterThan
on both HashMap
and LinkedHashMap
).
Further, if I had added the method to the original class one would be able to call this method on any HashMap
(even if the map contains two Strings) but the method is only applicable on a HashMap that contains String and Double or String and Int. Hence, I think it makes more sense to extend the original class and customize the current class with methods related to a HashMap
of String and Double.
Any suggestions?
Thanks