CoderTn
CoderTn

Reputation: 997

Sort a Java TreeSet using Comparator

i am trying to sort a TreeSet of objects ("Etudiant") using Comparator interface . This the Comparator implementation:

import java.util.Comparator;


public class TriParNom implements Comparator<Etudiant>{
    public int compare(Etudiant o1, Etudiant o2) {
        return o1.getNom().compareTo(o2.getNom());
    }
}

here is the the TreeSet declaration and the call of the comparator in the main :

TreeSet<Etudiant> University= new TreeSet<Etudiant>(new TriParNom());

the error i get in the main class when i declare the TreeSet and call the comparator ,is : no suitable constructor found for TreeSet(TriParNom) .

Any solutions please ? thanks in advance .

Upvotes: 1

Views: 4756

Answers (2)

Raj
Raj

Reputation: 936

If your code matches to the snippet given below, then it should run fine without problems. The moment you remove the part implements Comparator<Etudiant> from class TriParNom, you will get the error indicating suitable constructor not found. Now, one another silly way it could happen if you haven't recompiled your classes after you implemented the comparator to your TriParNom - but that's too obvious. Have your class that contins main method(that declares Treeset) imported java.util.TreeSet ?

import java.util.Comparator;
import java.util.TreeSet;

public class TreesetCheck {
    public static void main(String[] args) {
        TreeSet<Etudiant> University= new TreeSet<Etudiant>(new TriParNom());
    }
}

class TriParNom implements Comparator<Etudiant>{
    public int compare(Etudiant o1, Etudiant o2) {
        return o1.getNom().compareTo(o2.getNom());
    }
}

class Etudiant {
    public String getNom() {
        // TODO Auto-generated method stub
        return "some";
    }
}

Upvotes: 1

S3lvatico
S3lvatico

Reputation: 264

I tried a very simple implementation based on the information you provided, and I give you my results:

project structure

The Etudiant class is a very simple pojo

public class Etudiant {

private String nom;

public String getNom() {
    return nom;
}

public void setNom(String nom) {
    this.nom = nom;
}   }

The TriParNom class is the plain Comparator you described:

import java.util.Comparator;

public class TriParNom implements Comparator<Etudiant> {

    @Override
    public int compare(Etudiant o1, Etudiant o2) {
        return o1.getNom().compareTo(o2.getNom());
    }

}

And here is a simple class with an entry point and a sample method to exercise the newly created treeset

import java.util.TreeSet;

public class Main {

    public static void main(String[] args) {
        TreeSet<Etudiant> u = new TreeSet<>(new TriParNom());
        System.out.printf("size? %d%n", u.size());      
    }

}

Execution results follow:

exec

Apparently, there are no compilation errors either.

Upvotes: 2

Related Questions