public class Student {
private String name;
private int age;
set/get 有参的构造方法
}
public class Comparator implements java.util.Comparator {
private int compare(String a,String b){
// return a.compareTo(b);
return a.compareToIgnoreCase(b);
}
private int compare(int a,int b) { return a>b?(a<b?0:1):-1; }
@Override
public int compare(Object o1, Object o2) {
Student stu1 = (Student)o1;
Student stu2 = (Student)o2;
String name1 = stu1.getName();
String name2 = stu2.getName();
int age1 = stu1.getAge();
int age2 = stu2.getAge();
return (compare(name1, name2) == 0) ? (compare(age1, age2)) : (compare(
name1, name2));
}
}
public static void main(String[] args) {
Student p1 = new Student("aB", 4);
Student p2 = new Student("b", 2);
Student p3 = new Student("c", 1);
Student p4 = new Student("ab", 1);
Student p5 = new Student("aa", 6);
Student p6 = new Student("aC", -1);
List<Student> list = new ArrayList<Student>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
list.add(p6);
Collections.sort(list, new Comparator());
Iterator<Student> it = list.iterator();
while(it.hasNext()){
Student stu = it.next();
System.out.println(stu.getName()+":"+stu.getAge());
}
}
private String name;
private int age;
set/get 有参的构造方法
}
public class Comparator implements java.util.Comparator {
private int compare(String a,String b){
// return a.compareTo(b);
return a.compareToIgnoreCase(b);
}
private int compare(int a,int b) { return a>b?(a<b?0:1):-1; }
@Override
public int compare(Object o1, Object o2) {
Student stu1 = (Student)o1;
Student stu2 = (Student)o2;
String name1 = stu1.getName();
String name2 = stu2.getName();
int age1 = stu1.getAge();
int age2 = stu2.getAge();
return (compare(name1, name2) == 0) ? (compare(age1, age2)) : (compare(
name1, name2));
}
}
public static void main(String[] args) {
Student p1 = new Student("aB", 4);
Student p2 = new Student("b", 2);
Student p3 = new Student("c", 1);
Student p4 = new Student("ab", 1);
Student p5 = new Student("aa", 6);
Student p6 = new Student("aC", -1);
List<Student> list = new ArrayList<Student>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
list.add(p6);
Collections.sort(list, new Comparator());
Iterator<Student> it = list.iterator();
while(it.hasNext()){
Student stu = it.next();
System.out.println(stu.getName()+":"+stu.getAge());
}
}