java 树集字母排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15509234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 19:50:58  来源:igfitidea点击:

Treeset alphabetical sorting

javasortingtreeset

提问by A C

How do I get the treeset to sort alphabetically? And remove duplicates.. it's been driving me nuts for a day. Maybe I need to get some sleep..

如何让树集按字母顺序排序?并删除重复项......这让我发疯了一天。可能我需要睡一觉了。。

public static void main(String[] args) {
        String fileName = args[0];
        String words;
        Scanner s = null;
        Iterator itr;

        try {
            s = new Scanner(new BufferedReader(new FileReader(fileName)));
                while (s.hasNext()) {
                    words = s.next();

                    TreeSet<String> ts = new TreeSet<String>();
                    ts.add(words);

                    System.out.println(ts);
                }
            } catch (FileNotFoundException fnfe) {
            System.exit(0);
        } finally {
               if (s != null) {
                   s.close();
                }
            }
    }        

回答by emd

TreeSetholds the set in a tree structure which is automatically sorted in natural order. Every class that implements the Comparableinterface will be sorted. The String class implements the Comparableinterface already so you don't have to do anything to sort it, just add it to the TreeSet.

TreeSet将集合保存在按自然顺序自动排序的树结构中。每个实现Comparable接口的类都将被排序。String 类Comparable已经实现了该接口,因此您无需对其进行任何排序,只需将其添加到TreeSet.

Sets can't contain duplicates if the hashCode()and equals()methods are implemented how they should.

如果hashCode()equals()方法按照它们应该的方式实现,则集合不能包含重复项。

EDIT: The TreeSet<String> ts = new TreeSet<String>();is located in the while()loop scope. You are initializing it every loop and loosing the data drom the previous one. Declare it outside the loop and don't use Collection.sort()

编辑:TreeSet<String> ts = new TreeSet<String>();位于while()循环范围内。您在每个循环中都对其进行初始化并丢失前一个循环中的数据。在循环之外声明它并且不要使用Collection.sort()