Home > OS >  Can Collections.sort() take treeSet as first argument? If not why?
Can Collections.sort() take treeSet as first argument? If not why?

Time:05-23

I have my 'Person' class as follows -

public class Person implements Comparable<Person> {
    private int marks;
    private String name;

    Person(int marks, String name) {
        this.marks = marks;
        this.name = name;
    }

    public int getMarks() {
        return marks;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Person: Marks = "   marks   ", Name =  "   name;
    }

    @Override
    public int compareTo(Person person) {
        return marks > person.marks ? 1 : -1;
    }
}

Now in main method I have created another comparator with opposite sorting -

Comparator<Person> comparator = new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                int marks1 = p1.getMarks();
                int marks2 = p2.getMarks();
                return marks1 > marks2 ? -1 : 1;
            }
        };

Now, I create a TreeSet -

TreeSet<Person> treeSet1 = new TreeSet<>(List.of(
                new Person(67, "Himani"),
                new Person(73, "Hasani"),
                new Person(21, "Rohini")
        ));

Now, I try passing treeSet as an argument to Collections.sort() -

Collections.sort(treeSet1, comparator);

Here, I get the following error -


Required type                         Provided

list:List<T>                         TreeSet<Person>
                              
c:Comparator<? super T>              Comparator<Person>

As far as I can deduce from the error - Collections.sort() with comparator can only be used on List and not Set.

Am I correct? If not where am I going wrong? If yes why am I correct?

CodePudding user response:

The first argument to Collections.sort is of type List<T>. So you can only pass List objects to it, not Set objects, or anything else.

This is sensible. The reason is that Set objects are of two types.

  • There are those that are, by their nature, always unsorted, such as HashSet. It doesn't make sense to sort these.
  • There are those that are, by their nature, always sorted the same way, such as TreeSet. It doesn't make sense to sort these, because they're already sorted.

I think maybe what you want is to take your TreeSet and have it sorted using a different Comparator. To do that, you'll have to make a new TreeSet with your new Comparator, and copy the entries across from the old set using addAll.

  • Related