Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate a generic recursive class in Java

My problem is that I am using a class not developed by me (I took it from Microsoft Azure SDK for Java). The class is called Node and you can see it here.

As you can see the class is a generic class declared recursively like this:

public class Node<DataT, NodeT extends Node<DataT, NodeT>> {
      ...
}

When I try to instantiate it I don't know how to do it. I am doing this but I know IT IS NOT the way because it has no end:

Node<String, Node<String, Node<String, Node<...>>>> myNode = new Node<String, Node<String, Node<String, Node<...>>>>;

I hope you understand my question. Thanks.

like image 454
ycesar Avatar asked May 10 '17 13:05

ycesar


2 Answers

One way is to extend Node like:

class MyNode<T> extends Node<T, MyNode<T>> {
}

and then instantiate it like:

Node<String, MyNode<String>> node1 = new MyNode<String>();

or

MyNode<Integer> node2 = new MyNode<Integer>();
like image 173
Harmlezz Avatar answered Nov 10 '22 00:11

Harmlezz


You have to declare a class which extends Node so you can use the name of the class:

class StringNode extends Node<String, StringNode> {
}
like image 22
Radiodef Avatar answered Nov 09 '22 22:11

Radiodef