【问题标题】:TreeSet implementation?树集实现?
【发布时间】: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


【解决方案1】:

对于用户定义的对象,不能直接添加到 TreeSet。您需要给 TreeSet 一个属性,在该属性上应该适用排序。例如,您是根据speedLimit 还是speedRecorded 进行排序?我怎么知道? TreeSet 是怎么知道的?

要向 TreeSet 提供您需要提供我们称之为自定义比较器的信息。

请阅读以下文章,它们会对您有所帮助。

https://www.geeksforgeeks.org/treeset-comparator-method-in-java/

https://www.callicoder.com/java-treeset/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2016-11-02
    相关资源
    最近更新 更多