Once one architect in my office told me that difference between comparator and comparable is; Comparator compares between two different class objects where comparable compares within the same class. I have one Class Trainee and another Student class. I want to sort names inside Student and Trainee class at the same time. Student has few names and Trainee has few names. Want to sort all these names in natural order. Is this possible to achieve? Below is my code with error.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Student {
String empName;
Student(String empName) {
this.empName = empName;
}
}
class Trainee {
String studName;
Trainee(String studName) {
this.studName = studName;
}
}
public class Sort implements Comparator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student st = new Student("caroline");
Student st1 = new Student("elley");
Student st2 = new Student("fannah");
Trainee tr = new Trainee("aundh");
Trainee tr1 = new Trainee("Rohit");
Trainee tr2 = new Trainee("Shammi");
List list = new ArrayList<>();
list.add(st);
list.add(st1);
list.add(st2);
ArrayList list2 = new ArrayList<>();
list2.add(tr);
list2.add(tr1);
list2.add(tr2);
Collections.sort(Student, new Comparator<Trainee>() {
@Override
public int compare(Student s, Trainee t) {
// TODO return 1 if rhs should be before lhs
return s.empName.compareToIgnoreCase(t.studName);
}
});
}
}