【发布时间】:2021-05-28 16:47:00
【问题描述】:
我尝试实现 TreeSet 而不是 ArrayList,因为我需要对该列表进行排序。原来的代码是:
private final List<Report> reports = new ArrayList<Report>();
public void receiveReport(final Report report) {
this.reports.add(report);
}
我的版本:
private final TreeSet<Report> reports = new TreeSet<>();
public void receiveReport(final Report report) {
reports.add(report);
}
它只显示 1 份报告和此错误:
Exception in thread "main" java.lang.ClassCastException: class dsa.speedcamera.Report cannot be cast to class java.lang.Comparable (dsa.speedcamera.Report is in unnamed module of loader 'app';
java.lang.Comparable is in module java.base of loader 'bootstrap')
at java.base/java.util.TreeMap.compare(TreeMap.java:1563)
at java.base/java.util.TreeMap.addEntryToEmptyMap(TreeMap.java:768)
at java.base/java.util.TreeMap.put(TreeMap.java:777)
at java.base/java.util.TreeMap.put(TreeMap.java:534)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at dsa.speedcamera.ProvidedImplementation.receiveReport(ProvidedImplementation.java:19)
at dsa.speedcamera.ProvidedImplementation.demonstration(ProvidedImplementation.java:73)
at dsa.speedcamera.ProvidedImplementation.main(ProvidedImplementation.java:92)
Process finished with exit code 1
这是报告文件: 包dsa.speedcamera;
public class Report {
public TimeID timeID;
public int speedLimit;
public String carRegistration;
public int speedRecorded;
/**
* Returns a String representing the values in this object so that is can
* be directly printed with System.out.println();
*/
public String toString() {
return timeID.toString() +
"\nSpeed limit: " + speedLimit + " mph" +
"\nCar registration: " + carRegistration +
"\nSpeed recorded: " + speedRecorded + " mph";
}
}
我该怎么办?
【问题讨论】:
-
Report是一个类,这个类中必须有一些属性(整数,字符串)应该适用于排序。您需要将这些信息提供给 TreeSet,对吗? -
@Sim Sam 我编辑了,现在你可以看到报告类了
标签: sorting binary-search-tree treeset