我想实现以下目标.
我有一个泛型类Node<K,T,V>,如下所示:
public class Node<K,T,V>{
/**
* @return the key
*/
public K getKey() {
return key;
}
/**
* @param key the key to set
*/
public void setKey(K key) {
this.key = key;
}
// etc...
Run Code Online (Sandbox Code Playgroud)
现在我想要一个Tree在具有任意参数化类型的节点上运行的类:
public class Tree <Node<K,V,T>> {
public void insert(Node<K,V,T> node){
K key = node.getKey();
// do something...
}
// ... etc...
}
Run Code Online (Sandbox Code Playgroud)
然而,这不起作用,因为Eclipse告诉我线条public class Tree <Node<K,V,T>>看起来不太好:)如果我将其更改为
public class Tree <Node> {
Run Code Online (Sandbox Code Playgroud)
它告诉我类型Node正在隐藏Node类型.如何从Tree类中实现这一点我可以正确访问K,V和T类型?
我很确定这个问题已被回答了无数次.但是,我没有找到任何东西 - 对不起!
干杯.
您可以将树更改为:
class Tree<K, T, V> {
public void insert(Node<K, T, V> node) {
K key = node.getKey();
// do something...
}
// ... etc...
}
Run Code Online (Sandbox Code Playgroud)
或者如果要将其绑定到Node,
class Tree2<N extends Node<K, T, V>, K, T, V> {
public void insert(N node) {
K key = node.getKey();
// do something...
}
// ... etc...
}
Run Code Online (Sandbox Code Playgroud)