如何在Java';的子类中使用put();s树图

如何在Java';的子类中使用put();s树图,java,subclass,Java,Subclass,我想创建java.util.TreeMap类的子类,以便添加一个增量方法: 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 (!(

我想创建java.util.TreeMap类的子类,以便添加一个增量方法:

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
  }
}
我做错了什么



有关我采用的解决方案,请参阅。

如果要创建自定义树映射以独占方式处理
整数,则应使其扩展
树映射,而不是泛型类型
V

公共类CustomTreeMap扩展了TreeMap{
...
}
这样以后就不需要检查
实例了

如果密钥也需要是
整数
,请声明无泛型类型:

公共类CustomTreeMap扩展了TreeMap{
...
}

如果它应该是整数,则使用整数:

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
  }
}
公共类CustomTreeMap扩展了TreeMap{
公共无效增量(K键){
整数值;
如果(本文件包含密钥)){
对象值=this.get(键);
如果(!(整数的值实例)){
//失礼
返回;
}否则{
intValue=(整数)值;
intValue++;
}
}否则{
intValue=1;
}
this.put(key,intValue);//不能在树映射中应用put(Integer,Integer)
}
}

您将K和V都定义为泛型,为什么在它们实际上都是整数的情况下定义它们?
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
  }
}