Extend HashMap and LinkedHashMap at the same time?

I want to expand HashMapto add a method putIfGreaterThanthat 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 HashMapboth and LinkedHashMap. In other words, if someone creates an instance:

HashMap hashmap = new HashMap();

They must have access to the method:

hashmap.putIfGreaterThan();

And if someone creates an instance:

LinkedHashMap linkedhashmap = new LinkedHashMap();

They must have access to 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 HashMapnot LinkedHashMap. This would not allow me to access the method if I create an instance LinkedHashMap.

HashMap ( putIfGreaterThan), , ( , , , HashMap, , putIfGreaterThan HashMap, LinkedHashMap).

, , HashMap ( ), HashMap, String String Int. , , , HashMap String Double.

?

+4
3

Map , :

public class MyMap implements Map<String, Double>{
    private final Map<String, Double> map;  

    public MyMap(Map<String, Double> map){
        this.map = map;
    }

    public void putIfGreaterThan(String key, Double value ){...}

    @Override
    public int size() {
        return map.size();
    }

    //inherited methods
}

:

MyMap map = new MyMap(new LinkedHashMap<>());

MyMap map = new MyMap(new HashMap<>());
+2

Java , .

Java

0

HashMap LinkedHashMap. - MyHashMap<K,V>, Map, HashMap () LinkedHashMap MyHashMap.

0
source

Source: https://habr.com/ru/post/1672016/


All Articles