【问题标题】:How do I reverse the order of the data in a TreeSet instance?如何反转 TreeSet 实例中数据的顺序?
【发布时间】:2012-10-09 06:49:15
【问题描述】:

我有一个名为 Dictionary 的类,它是排序字符串的集合。该类是 TreeSet 类的扩展,这意味着它使用 Comparator 进行排序。我想有一个反向方法来反转数据集的顺序,但不幸的是这是不可能的,因为 TreeSet 在初始化后无法更改它的 Comparator 。作为一种解决方法,我尝试使用原始 Comparator 的反转版本创建一个新的 Dictionary 实例,但我无法想出任何方法将 this 指向新对象。

这可能吗?也许是一个完全不同的解决方案?

public void reverse() {
    Dictionary reversed = new Dictionary(this, Collections.reverseOrder());
    this = reversed; // Obviously not working, but is pretty much what I want to do.
    reversed.storeOnFile("descending.txt");
}

【问题讨论】:

  • 为什么不使用TreeSet.descendingSet()

标签: java treeset


【解决方案1】:

考虑从您的反向方法返回新的Dictionary

public Dictionary reverse(){
    return new Dictionary(this, Collections.reverseOder());
}

或者从该方法返回一个ListSet 视图。

【讨论】:

    【解决方案2】:

    将您的类从可变的转换为不可变的。这就是你现在正在做的事情:

    Dictionary dic = new Dictionary();
    dic.reverse();
    

    这是你应该做的:

    Dictionary forward = new Dictionary();
    Dictionary reverse = forward.reverse();
    

    一般来说,immutable objects 是首选。

    【讨论】:

    • 如果词典需要添加更多单词怎么办?
    猜你喜欢
    • 2016-04-07
    • 1970-01-01
    • 2019-06-15
    • 2016-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多