ads3rdaccount ads3rdaccount - 2 months ago 8
Java Question

generic type scope does not apply to inner class?

I have the following code where type T extends Comparable, but I get a compile error when I try to do


root.node.compareTo(min).


Saying compareTo does not apply. It seems generic type scope does not apply to inner class?

public class Tree<T extends Comparable> {
public class Node<T>{
private T node;
private Node<T> left;
private Node<T> right;
public Node(T node, Node<T> left, Node<T> right) {
super();
this.node = node;
this.left = left;
this.right = right;
}
}
public boolean isBalanced(Node<T> root){
return isBalanced(root, Integer.MIN, Integer.MAX);
}
private boolean isBalanced(Node<T> root, T min, T max){
if(root == null){
return true;
}
if(root.node.compareTo(min) < 0 || root.node.compareTo(max) > 0){
return false;
}
return isBalanced(root.left, min, root.node) || isBalanced(root.right, root.node, max);
}
}

Answer

When you say public class Node<T>, you're shadowing the <T> from the outer class. You should either remove the <T> from the inner class declaration or, better, make the inner class a static nested class (since there's no inherent reason the node needs to know about the tree it's attached to).

(Note: Also use <T extends Comparable<T>>.)