我尝试实现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);
}它只向我显示一个报告和这个错误:
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这是报表文件: package 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";
}
}我该怎么办?
发布于 2021-05-29 01:07:36
对于用户定义的对象,不能直接添加到TreeSet。您需要为TreeSet提供一个排序应该适用的属性。例如,您是基于speedLimit还是基于speedRecorded进行排序?我怎么知道?TreeSet是怎么知道的?
要向TreeSet提供该信息,您需要提供我们所称的自定义比较器。
请阅读下面的文章,它们会对你有所帮助。
https://www.geeksforgeeks.org/treeset-comparator-method-in-java/
https://stackoverflow.com/questions/67742756
复制相似问题