【发布时间】: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()?