我有一个名为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");
}
答案 0 :(得分:3)
考虑从您的反向方法返回新的Dictionary
。
public Dictionary reverse(){
return new Dictionary(this, Collections.reverseOder());
}
或者从方法中返回List
或Set
视图。
答案 1 :(得分:1)
将您的类从mutable转换为immutable。这就是你现在正在做的事情:
Dictionary dic = new Dictionary();
dic.reverse();
这是你应该做的:
Dictionary forward = new Dictionary();
Dictionary reverse = forward.reverse();
一般来说,immutable objects是首选。