问题
I have a class called Dictionary which is a collection of sorted strings. This class is an extension of the TreeSet class, which means that it uses a Comparator for the sorting. I want to have a reverse method for reversing the order of the data set, but this is unfortunately not possible since TreeSet can't change it's Comparator after initialization. As a workaround I tried to create a new Dictionary instance using a reversed version of the original Comparator, but I can't come up with any way to point this
to the new object.
Is this possible? Maybe an entirely different solution?
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");
}
回答1:
Consider returning the new Dictionary
from your reverse method.
public Dictionary reverse(){
return new Dictionary(this, Collections.reverseOder());
}
Or return a List
or Set
view from the method.
回答2:
Convert your class from mutable to immutable. This is what you're doing now:
Dictionary dic = new Dictionary();
dic.reverse();
This is what you should do:
Dictionary forward = new Dictionary();
Dictionary reverse = forward.reverse();
In general, immutable objects are preferred.
来源:https://stackoverflow.com/questions/12960970/how-do-i-reverse-the-order-of-the-data-in-a-treeset-instance