jeudi 13 août 2015

Internal working of Comparator [on hold]

Can you please explain how sorting is performed here using Comparator? Can you make a simple step by step explanation for Collections.sort(al, Student.StuNameComparator);?

Student class:

public class Student {
    private String name;
    private int rollno;

    public Student(int rollno, String name) {
        this.rollno = rollno;
        this.name = name;
    }

    public static Comparator<Student> StuNameComparator = new Comparator<Student>() {
        public int compare(Student s1, Student s2) {
            return s1.name.compareTo(s2.name);
        }
    };

    public String toString() {
        return "Roll No: " + rollno + " Name: " + name;
    }
}

main method:

public static void main(String args[]) {
   ArrayList<Student> al = new ArrayList<Student>();
   al.add(new Student(983, "AAA" ));
   al.add(new Student(981, "KKK" ));
   al.add(new Student(999, "BBB"));

   System.out.println("Student Name Sorting:");
   Collections.sort(al, Student.StuNameComparator);

   for(Student str: al) {
        System.out.println(str);
   }
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire