I have the following code where I have a Treeset, to which if I pass my comparator it works fine. however, if I construct my Treeset and then call collections.sort, I get compile error. 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. I know StringBuffer is a bad type to keep as element in Set. However, I was testing if Java allows to keep a mutable object in Set. (python does not allow mutable object to placed in set or dictionary(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).
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.
Collections.sort expects a List rather than a Set. Try this instead
Set<StringBuffer> sb=new TreeSet<StringBuffer>(new SbufferComparator());
and remove the call to sort completely
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With