gpt4 book ai didi

java - 比较已实现可比较的类的对象

转载 作者:行者123 更新时间:2023-12-02 05:37:28 25 4
gpt4 key购买 nike

我正在学习二叉搜索树并尝试用 Java 实现它。

    public class BinarySearchTree<T>
{
private class Node
{
public T data;
public Node left;
public Node right;
}

//some code goes here

public void insert(T data)
{
//make a new node and add data to that node
//call to recursive function
}
private Node ins(Node root,Node toBeInserted)
{
if(root==null) { root = tobeInserted; return root; }

//problem is here...
else if(toBeInserted.data<=root.data)// <----How to do this ?????
root = ins(root.left,toBeInserted);
else
root = ins(root.right,toBeInserted);
return root;
}
//some more code
}

问题是如何比较T类的对象?如果我在某个类 T 中实现了可比较,那么如何比较存储在左右节点中的数据???

提前致谢。

最佳答案

如果T始终实现Comparable,您可以在其定义中添加适当的绑定(bind):

public class BinarySearchTree<T extends Comparable<T>> { ... }

然后你可以使用compareTo():

toBeInserted.data.compareTo(root.data) <= 0

关于java - 比较已实现可比较的类的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24839725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com