简体   繁体   English

如何在Java的TreeMap的子类中使用put()

[英]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: 我想创建一个java.util.TreeMap类的子类,以允许我添加一个increment方法:

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: Android Studio 1.0.2首先提出put(K Key, V Value)用于自动完成,后来警告:

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 : 如果要创建自定义树形图以独占处理Integers ,则应使其扩展TreeMap<K, Integer> ,而不是泛型类型V

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

This way you don't need the instanceof check later. 这样您以后就不需要执行instanceof检查。

If your key also needs to be an Integer , declare no generic types instead: 如果您的密钥也需要是Integer ,则不要声明泛型类型:

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

If it should be Integer then use Integer: 如果它应该是Integer,那么使用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
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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