How do I reverse the order of the data in a TreeSet instance?

China☆狼群 提交于 2019-12-11 10:28:52

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!