package bstmap;
import java.util.Iterator;
import java.util.Set;
public class BSTMap<K extends Comparable<K>, V> implements Map61B<K, V>{
private static class Node <K, V>{
private final K key;
private final V value;
private Node left;
private Node right;
private Node(K key, V value) {
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
}
private Node root;
private int size;
public BSTMap() {
root = null;
size = 0;
}
@Override
public boolean containsKey(K key) {
Node current = root;
while (current != null) {
if (current.key.equals(key)) {
return true;
}
if (current.key.compareTo(key) < 0) {
current = current.right;
} else {
current = current.left;
}
}
return false;
}
There is an error at “current.key.compareTo(key)”.
I had already created a bounded type parameter at the class header BSTMap where K should extends Comparable but why there’s still an error at the line of invoking compareTo method on key of type K.
I found out that to resolve this error I must explicitly declare that K extends Comparable again at the header for inner class Node but I thought Java should be able that K extends Comparable automatically upon declaring it at the BSTMap header and this applies to all other methods I am creating. Thus, may I know when should I explicitly declare a bounded type parameter in a class other than specifying it at the class header?