简体   繁体   中英

How to use put() in a subclass of Java's TreeMap

I want to create a subclass of class of java.util.TreeMap, to allow me to add an increment method:

public class CustomTreeMap<K, V> extends TreeMap<K, V> {
  public void increment(Integer key) {
    Integer intValue;

    if (this.containsKey(key)) {
      Object value = this.get(key);
      if (!(value instanceof Integer)) {
        // Fail gracefully
        return;

      } else {
        intValue = (Integer) value;
        intValue++;
      }
    } else {
      intValue = 1;
    }

    this.put(key, intValue); // put(Integer, Integer) cannot be applied in TreeMap
  }
}

Android Studio 1.0.2 first proposes put(K Key, V Value) for autocompletion, and later warns that:

put(K, V) cannot be applied in TreeMap to (java.lang.integer, java.lang.integer)

What is it that I am doing wrong?


See here for the solution I adopted.

If you want to create your custom treemap to handle Integers exclusively, you should make it extend TreeMap<K, Integer> , not the generic type V :

public class CustomTreeMap<K> extends TreeMap<K, Integer> {
  ...
}

This way you don't need the instanceof check later.

If your key also needs to be an Integer , declare no generic types instead:

public class CustomTreeMap extends TreeMap<Integer, Integer> {
  ...
}

If it should be Integer then use Integer:

public class CustomTreeMap<K> extends TreeMap<K, Integer> {
  public void increment(K key) {
    Integer intValue;

    if (this.containsKey(key)) {
      Object value = this.get(key);
      if (!(value instanceof Integer)) {
        // Fail gracefully
        return;

      } else {
        intValue = (Integer) value;
        intValue++;
      }
    } else {
      intValue = 1;
    }

    this.put(key, intValue); // put(Integer, Integer) cannot be applied in TreeMap
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM