import java.util.Collections;
import java.util.Comparator;
public class ComparatorComparableExample {
public static void main(String[] args){
Student s1 = new Student(10, "john", 500.50f);
Student s2 = new Student(1, "Abc", 700);
Student s3 = new Student(7, "xyz", 800);
ArrayList al = new ArrayList();
al.add(s1);
al.add(s2);
al.add(s3);
MyClass m =new MyClass();
Collections.sort(al,m);
for(Object o: al){
Student s = (Student)o;
s.display();
}
}
static class Student /*implements Comparable */{
Student(int id, String name, float salary){
this.id = id;
this.name =name;
this.salary = salary;
}
void display(){
System.out.println(id + ":" + name + ":" + salary);
}
int id;
String name;
float salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
/*
@Override
public int compareTo(Object o) {
Integer i1 = id;
Student i2 = (Student) o;
return i1.compareTo(i2.getId());
}
*/
}
static class MyClass implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return ((Integer)s1.getId()).compareTo(s2.getId());
}
}
}
No comments:
Post a Comment