![](/img/trans.png)
[英]How to use Strings for .get() and .put() with TreeMap in Java
[英]How to use put() in a subclass of Java's TreeMap
我想创建一个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首先提出put(K Key, V Value)
用于自动完成,后来警告:
put(K, V) cannot be applied in TreeMap to (java.lang.integer, java.lang.integer)
我做错了什么?
请参阅此处了解我采用的解决方案。
如果要创建自定义树形图以独占处理Integers
,则应使其扩展TreeMap<K, Integer>
,而不是泛型类型V
:
public class CustomTreeMap<K> extends TreeMap<K, Integer> {
...
}
这样您以后就不需要执行instanceof
检查。
如果您的密钥也需要是Integer
,则不要声明泛型类型:
public class CustomTreeMap extends TreeMap<Integer, 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.