Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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))

like image 935
brain storm Avatar asked Aug 27 '26 21:08

brain storm


2 Answers

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.

like image 162
assylias Avatar answered Aug 29 '26 12:08

assylias


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

like image 23
Reimeus Avatar answered Aug 29 '26 12:08

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!