简体   繁体   English

T上的初学者Java Q扩展了可比T

[英]Beginner Java Q on T extends Comparable T

I am a beginner in learning to code in java and was implementing a Red Black Tree data structure. 我是学习用Java编写代码的初学者,并且正在实现Red Black Tree数据结构。 I created a class for the node inside the Main class and used T extends Comparable T. 我为Main类中的节点创建了一个类,并使用T扩展了ComparableT。

However, the following line 但是,以下行

RedBlackNode<T> nil =new RedBlackNode<T>(mainkey);

is giving an error as it is not identifying usage of "T" datatype. 由于未标识“ T”数据类型的使用而给出了错误。 I am trying hard to learn usage of Comparable and unable to fix this. 我正在努力学习Comparable的用法,但无法解决此问题。 Any help would be appreciated 任何帮助,将不胜感激

public class Main {

    public void main(String[] args) {
        System.out.println("Hello World! qNew");
        int mainkey=10;
        System.out.println(mainkey);
        RedBlackNode<T> nil =new RedBlackNode<T>(mainkey);
        //RedBlackNode<T> root=nil;
        //System.out.println(nil.key);
    }
    public class RedBlackNode<T extends Comparable <T>>
    {
        public static final int BLACK = 0;  //Enumerating Colors with numbers for
        public static final int RED = 1;     // Color of node
        public T key;

        RedBlackNode<T> parent;  //Parent Node
        RedBlackNode<T> left;    //Left Child Node
        RedBlackNode<T> right;   //Right Child Node

        public int numLeft=0;     //No of elements to left of a node
        public int numRight=0;     //No of elements to right of a node

        public int color;       //Color of each node

        //Default constructor to initialize

        RedBlackNode()
        {
            color=BLACK;
            numLeft=0;
            numRight=0;
            parent=null;
            left=null;
            right=null;
        }

        //Constructor to initialize key value of the node

        RedBlackNode(T key)
        {
            this();
            this.key=key;
        }
    }

}

T represents whatever you want it to be. T代表您想要的一切。 When writing the class, you use capitals like T or G, BUT when you use it, it needs to know what that T is. 编写类时,使用大写字母T或G,但是使用大写字母时,它需要知道T是什么。

If I had a Person class as the data in the node, I'd use it like this RedBlackNode<Person> parent = new RedBlackNode<Person>(); 如果我有一个Person类作为节点中的数据,则可以像这样使用它RedBlackNode<Person> parent = new RedBlackNode<Person>();

Actually this worked: 实际上,这可行:

RedBlackNode nil = new RedBlackNode(mainkey);

It seems that by skipping the datatype, Java automatically uses the one provided as argument 似乎通过跳过数据类型,Java自动使用提供的那个作为参数。

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

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