import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Comparable_Comparator {
public static void main(String... args) throws Exception {
sortA();
}
private static void sortA() {
// TODO Auto-generated method stub
List<A> list = new ArrayList<A>();
list.add(new A(22));
list.add(new A(10));
list.add(new A(6));
list.add(new A(33));
list.add(new A(21));
System.out.println(list);
Collections.sort(list);
System.out.println(list);
List<B> list2 = new ArrayList<B>();
list2.add(new B(22));
list2.add(new B(10));
list2.add(new B(6));
list2.add(new B(33));
list2.add(new B(21));
System.out.println(list2);
Collections.sort(list2,new MyCompator());
System.out.println(list2);
}
}
class A implements Comparable<A>{
private int age;
public A(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(A o) {
// TODO Auto-generated method stub
return this.age-o.age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.age+"";
}
}
class B {
private int age;
public B(int age) {
super();
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return this.age+"";
}
}
class MyCompator implements Comparator<B>{
public int compare(B o1, B o2) {
// TODO Auto-generated method stub
return o1.getAge()-o2.getAge();
}
}