问题
If I have a node class(es) that can accept a generic type for it's key value:
class Node<K extends Comparable<K>> implements Comparable<Node<K> {
...
}
class KeyValueNode<K extends Comparable<K>, V> extends Node<K> {
...
}
Is it possible to declare a generic binary tree class that accepts a generic type of node, which can contain a generic type of key value? I thought it would look something like this....
class BinaryTree<N<K>> {
N<K> root;
BinaryTree<N<K>> left, right;
...
}
Apologies for any glaring misunderstandings, I'm still trying to get the hang of generics and the syntax in Java, would greatly appreciate any help or insights.
Thanks!
回答1:
A binary tree structure will essentially just hold a reference to the root node. So it should have the same type parameters as its nodes:
class BinaryTree<K extends Comparable<K>> {
Node<K> root;
}
Or for the key-value design:
class KeyValueBinaryTree<K extends Comparable<K>, V> {
KeyValueNode<K, V> root;
}
Note that it's debatable whether an enclosing tree class is necessary, since it's the nodes that are pointing to each other.
回答2:
You can say:
class BinaryTree<N extends Node<N>> {
Node<N> root;
// or even better: N root;
BinaryTree<N> left, right;
}
Having BinaryTree<Node<K>>
is not parameterizing the class as is the purpose of defining a generic type.
回答3:
This is how I would write a generic binary tree class
public class BinaryTree<N extends Node<K>, K extends Comparable> {
N root;
BinaryTree<N, K> left, right;
}
(Although I assume you would not really story the BinaryTree in a binary tree and that was just for your example to show how it could be declared)
来源:https://stackoverflow.com/questions/10265836/declare-a-binary-tree-which-takes-a-generic-type-of-node-which-contains-a-generi