import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class test7 {
public static void main(String[] args) throws IOException {
/////////////////////////////////////////////////////////////
// comparable
ArrayList<Student> stlist = new ArrayList<Student>();
stlist.add(new Student("test1", 10));
stlist.add(new Student("test2", 9));
stlist.add(new Student("test3", 8));
stlist.add(new Student("test4", 7));
Collections.sort(stlist);
for (Student s : stlist) {
System.out.println(s.age);
}
/////////////////////////////////////////////////////////////
// comparator
ArrayList<Students> stslist = new ArrayList<Students>();
stslist.add(new Students("test1", 10));
stslist.add(new Students("test2", 9));
stslist.add(new Students("test3", 8));
stslist.add(new Students("test4", 7));
Collections.sort(stslist, new Comparator<Students>() {
@Override
public int compare(Students o1, Students o2) {
if (o1.age < o2.age) {
return -1;
} else if (o1.age > o2.age) {
return 1;
}
return 0;
}
});
for (Students s : stslist) {
System.out.println(s.age);
}
}
}
class Student implements Comparable<Student> {
public String name;
public int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public int compareTo(Student o) {
if (this.age < o.age) {
return -1;
} else if (this.age > o.age) {
return 1;
}
return 0;
}
}
class Students {
public String name;
public int age;
public Students(String name, int age) {
this.name = name;
this.age = age;
}
}