Java二叉树,Node如何实现?

发布于 2024-08-05 09:51:58 字数 166 浏览 2 评论 0原文

在树类中,我应该比较两个节点,因为您知道搜索和添加项目。我对如何使其具有可比性有一些问题。当向树添加数据(通用的,任何东西)时,我们调用 Tree 类,然后该类创建一个新的 Node 对象。如何在 Node 类中声明变量数据/元素,使其为 E 类型(任何类型)并且仍然可比较?说真的,我来回尝试过,但没有得出任何结论。

In the tree class I'm suppose to compare two node, for you know searching and adding items. I have some issues with how to make it comparable. When one adds data(generic, anything) to the tree one calls the Tree class which then makes a new Node object. How can I declare the variable data/element in the Node class so that it is of type E (anything) and still Comparable? Seriously, I've tried back and forth without concluding with anything.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泪意 2024-08-12 09:51:58

并非一切都可以比较。你的要求是自相矛盾的。您可以通过声明通用参数来将 E 限制为可比较的,如下所示:

< E extends Comparable<E> >

这样,该类的使用者就可以使用所有实现了 Comparable 接口的类。您将能够访问键入 E 的内容的 compareTo 方法。

Not everything is Comparable. Your requirement is self-contradictory. You can constrain E to be comparable by declaring the generic parameter like:

< E extends Comparable<E> >

This way, the consumer of the class can use all classes that implement Comparable interface with it. You'll be able to access the compareTo method on things typed E.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文