Reputation: 7082
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.
Upvotes: 1
Views: 437
Reputation: 2690
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
}
}
Upvotes: 1
Reputation: 22156
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> {
...
}
Upvotes: 2