简体   繁体   English

泛型类型范围不适用于内部类吗?

[英]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 我在T类型扩展Comparable的地方有以下代码,但是在尝试执行此操作时出现编译错误

root.node.compareTo(min). root.node.compareTo(min)。

Saying compareTo does not apply. 说compareTo不适用。 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);
    }
}

When you say public class Node<T> , you're shadowing the <T> from the outer class. 当您说public class Node<T> ,您正在遮蔽外部类的<T> 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). 您应该从内部类声明中删除<T> ,或者最好使内部类成为静态嵌套类(因为没有内在的原因,节点无需知道它所连接的树)。

(Note: Also use <T extends Comparable<T>> .) (注意:还要使用<T extends Comparable<T>> 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM