ClassCastException,带有用于学生名单的二叉搜索树的查找方法

时间:2018-04-16 13:05:38

标签: java binary-search-tree

我在为二叉搜索树实现find方法时遇到了麻烦。我实现了自己的通用二叉搜索树版本,并创建了一个学生名单。名单使用二叉搜索树。但是,尝试按ID查找学生会给我一个ClassCastException错误。不确定为什么会这样,我可以在find方法中更改哪些方法让它正常工作?我可以看到它正在尝试将Student转换为String,但不知道如何正确修复它。我想这可能是因为在我的通用find方法中,它使用e作为与Student相比较的字符串,如何将字符串与Student ID中的字符串进行比较,而不是对象本身?

错误:

run:
Exception in thread "main" java.lang.ClassCastException: homework5.Student             
cannot be cast to java.lang.String
    at java.lang.String.compareTo(String.java:111)
    at homework5.BST.find(BST.java:16)
    at homework5.Roster.find(Homework5.java:175)
    at homework5.Homework5.lookupStudent(Homework5.java:44)
    at homework5.Homework5.main(Homework5.java:13)
C:\Users\Devin\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: 
Java returned: 1
BUILD FAILED (total time: 0 seconds)

BST.java查找方法:

// Generic find method
public Node find(E e) {
    Node<E> current = root;

    // Loop until e.compare to current element is not equal to 0
    while (e.compareTo(current.element) != 0) {
        // if e.compare is less than 0 set current to current.left
        if (e.compareTo(current.element) < 0) {
            current = current.left;
        } // else if current is 0 or greater than 0 set current 
        // to current.right
        else {
            current = current.right;
        }
        // if current is null, return null
        if (current == null) {
            return null;
        }
    }
    // return current value when loop ends
    return current;
}

主要方法:

public class Homework5 {

    static Roster rost = new Roster();

    public static void main(String[] args) {

        addStudent();
        //displayAllStudents();
        lookupStudent("11114");
    }
}

lookUpStudent方法:

// lookup a student in the roster
static void lookupStudent(String id) {
    if (rost.find(id) != null) {
        System.out.println(id + " found");
    } else {
        System.out.println(id + " not found");
    }
}

Roster.class:

class Roster {

    Student root;
    int numStudents;

    BST roster = new BST();

    public Roster() {
        root = null;
        numStudents = 0;
    }

    public void addStudent(Student st) {
        roster.insert(st);
        numStudents++;
    }

    public Student find(String id) {
        roster.find(id);
        return null;
    }

1 个答案:

答案 0 :(得分:0)

您要将student对象添加到addStudent()中的树,但使用字符串ID来查找它,因此e.compareTo(...)尝试将StringStudent进行比较,因此错误

将函数find改为smth,就像这样

public Student find(String id) {
  return roster.find(new student(id));
}

让学生实施Comparable界面并覆盖compareTo方法

public class Student implements Comparable<Student> {

  @Override
  public int compareTo(Student other) {
    return this.id.compareTo(other.getId());
  }
}