简体   繁体   English

在Java中将比较器传递给collections.sort()?

[英]passing comparator to collections.sort() in Java?

I have the following code where I have a Treeset, to which if I pass my comparator it works fine. 我有以下代码,我有一个Treeset,如果我通过我的比较器,它工作正常。 however, if I construct my Treeset and then call collections.sort, I get compile error. 但是,如果我构造我的Treeset然后调用collections.sort,我会得到编译错误。 my code is here 我的代码在这里

import java.util.*;

public class ComparatorExample {
private static class SbufferComparator implements Comparator<StringBuffer> {

        @Override
        public int compare(StringBuffer s1, StringBuffer s2) {
            return s1.toString().compareTo(s2.toString());

        }

}


    public static void main(String[] args) {
            StringBuffer one = new StringBuffer("one");
            StringBuffer  two = new StringBuffer("two");
            StringBuffer three = new StringBuffer("three");
            Set<StringBuffer> sb=new TreeSet<StringBuffer>();
             //The below line works
            //Set<StringBuffer> sb=new TreeSet<StringBuffer>(new SbufferComparator());
            sb.add(one);
            sb.add(two);
            sb.add(three);
            System.out.println("set before change: "+ sb);
            //This does not work
            Collections.sort(sb, new SbufferComparator());
            System.out.println("set After change: "+ sb);
        }
    }

PS. PS。 I know StringBuffer is a bad type to keep as element in Set. 我知道StringBuffer是一个bad类型,可以作为Set中的元素保留。 However, I was testing if Java allows to keep a mutable object in Set. 但是,我正在测试Java是否允许在Set中保留一个可变对象。 (python does not allow mutable object to placed in set or dictionary(map)) (python不允许将可变对象放在集合或字典中(map))

Collections.sort() can only be applied to a List , and you are passing a Set so it fails (it should not compile at all). Collections.sort()只能应用于List ,并且您正在传递一个Set因此它失败(它根本不应该编译)。

TreeSet is a sorted Set , so you should create it with an appropriate Comparator and the content of the set will always be sorted, without the need to manually sort it. TreeSet是一个有序Set ,因此您应该使用适当的Comparator创建它,并且该集合的内容将始终排序,而无需手动对其进行排序。

Collections.sort expects a List rather than a Set . Collections.sort需要List而不是Set Try this instead 试试这个

Set<StringBuffer> sb=new TreeSet<StringBuffer>(new SbufferComparator());

and remove the call to sort completely 并删除完全sort的调用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM