【问题标题】:Adding custom objects to binary search tree将自定义对象添加到二叉搜索树
【发布时间】:2014-04-18 17:28:41
【问题描述】:

我对泛型和二叉搜索树还很陌生,我正在尝试将自定义 Student 对象添加到 BST,但不知道如何实现它。我的Student 类声明如下:

class Student <E>implements Serializable, Comparable {

int studentNumber;

String firstName;
String lastName;
String major;
double gpa;

Student leftChild;
Student rightChild;

public Student() {
    this(0, "", "", "", 0.0);
} // end no-argument studentNumberRecordSerializable constructor

public Student(int sNum, String first, String last, String major, double gpa) {
    setstudentNumber(sNum);
    setFirstName(first);
    setLastName(last);
    setMajor(major);
    setGPA(gpa);
} // end four-argument studentNumberRecordSerializable constructor
....

然后是我的 Node 类:

class TreeNode<E extends Comparable<E>> {

TreeNode<E> leftNode;
E data;
TreeNode<E> rightNode;

public TreeNode(E nodeData) {
    data = nodeData;
    leftNode = rightNode = null; 
} // end TreeNode constructor

public void insert(E insertValue) {

    if (insertValue.compareTo(data) < 0) {

        if (leftNode == null)
            leftNode = new TreeNode<E>(insertValue);
        else
            leftNode.insert(insertValue);
    } // end if
....

然后我试图声明Tree&lt;Student&gt; tree = new Tree&lt;Student&gt;();,它是说那个学生是一个无效的论点。我还想调用tree.insertNode(new Student(studentNumber, firstName, lastName, major, gpa));将其添加到节点。是否有我没有遵循的额外步骤或我做错了什么?我对仿制药和 BST 进行了大量研究,但我在将两者联系在一起时遇到了麻烦。请帮忙!

【问题讨论】:

    标签: java generics binary-search-tree


    【解决方案1】:

    修复Student类声明:

    class Student implements Serializable, Comparable<Student> {
    

    【讨论】:

    • 我也需要在创建树的类中实现 Comparable 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2022-06-13
    • 1970-01-01
    相关资源
    最近更新 更多