Java - 使用 Comparable 的静态泛型类型
好吧,所以我一直在尝试实现一个简单的二叉搜索树,默认情况下使用可比较的数据类型。
忽略类中的所有其他方法,这是我认为非常标准的一般设置:
public class BSTNode<E extends Comparable<? super E>>{
E data;
BSTNode<E> left;
BSTNode<E> right;
//and I'm trying to define a static method(inside of the class) like this:
public static <E> String displayAscending(BSTNode<E> node){}
}
但编译器不喜欢它。现在,我对泛型类型有点陌生,所以我将解释我对其作用的理解,这可能会帮助您找出我的想法有什么问题。
E 扩展可比较 所以基本上一个对象 E 是 Comparable 的扩展。 Comparable 具有一个作为 E 祖先的元素,这本质上是一种抽象方式,表示 E 可以使用 Comparable 接口与其其他元素进行比较。
然后在我的静态方法中,我尝试递归地传递 BSTNode。我似乎无法理解为什么它不起作用。我知道如果我通过 BSTNode
它工作正常,但这似乎很危险。如果有人可以向我解释为什么这不起作用,我可以尝试找到另一种解决方案。
Alright, so I've been trying to implement a simple binary search tree that uses a comparable data type by default.
Ignoring all my other methods in the class, this is the general setup I have which I think is pretty standard:
public class BSTNode<E extends Comparable<? super E>>{
E data;
BSTNode<E> left;
BSTNode<E> right;
//and I'm trying to define a static method(inside of the class) like this:
public static <E> String displayAscending(BSTNode<E> node){}
}
But the compiler isn't liking it. Now, I'm kind of new to generic types so I'll explain my understanding of what this does and that might help you in figuring out what's wrong with my thinking.
E extends Comparable
So basically an object E that is an extension of Comparable. Comparable having an element that is an ancestor of E, which essentially is an abstract way of saying E can be compared with its other elements using the Comparable interface.
Then in my static method I'm trying to pass the BSTNode recursively. I can't seem to wrap my head around why it's not working. I know If I pass BSTNode<?>
it works fine, but that seems dangerous. If someone could explain to me WHY this isn't working I could try and find another solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个
try this