public class Student implements Comparable {
private int id;
private String name;
public Student() {
super();
}
@Override
public int compareTo(Object obj) {
if (obj instanceof Student) {
Student stu = (Student) obj;
return id - stu.id;
}
return 0;
}
@Override
public String toString() {
return "<" + id + ", " + name + ">";
}
}
public class CompareTest {
public static void main(String[] args) {
Student stu1 = new Student(1, "Little");
Student stu2 = new Student(2, "Cyntin");
Student stu3 = new Student(3, "Tony");
Student stu4 = new Student(4, "Gemini");
Student[] stus = new Student[4];
stus[0] = stu1;
stus[1] = stu4;
stus[2] = stu3;
stus[3] = stu2;
System.out.println(“Array: ” + Arrays.toString(stus));
Arrays.sort(stus);
System.out.println(“Sort: ” + Arrays.toString(stus));
}
}
public void sortByName () {
Student stu1 = new Student(1, "Little");
Student stu2 = new Student(2, "Cyntin");
Student stu3 = new Student(3, "Tony");
Student stu4 = new Student(4, "Gemini");
Student[] stus = new Student[4];
stus[0] = stu1;
stus[1] = stu4;
stus[2] = stu3;
stus[3] = stu2;
System.out.println("Array: " + Arrays.toString(stus));
Arrays.sort(stus, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Student && o2 instanceof Student) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
//return s1.getId() - s2.getId(); // 按Id排
return s1.getName().compareTo(s2.getName()); // 按姓名排
}
return 0;
}
});
System.out.println("Sorted: " + Arrays.toString(stus));
}
/**
* 使用自然排序
* Student必须实现Comparable接口,否则会抛出ClassCastException
*/
public void testSortedSet3() {
Student stu1 = new Student(1, "Little");
Student stu2 = new Student(2, "Cyntin");
Student stu3 = new Student(3, "Tony");
Student stu4 = new Student(4, "Gemini");
SortedSet set = new TreeSet();
set.add(stu1);
set.add(stu3); // 若Student没有实现Comparable接口,抛出ClassCastException
set.add(stu4);
set.add(stu2);
set.add(stu4);
set.add(new Student(12, "Little"));
System.out.println(set);
}
/**
* 使用比较器排序
* Student可以只是个简单的Java类,不用实现Comparable接口
*/
public void testSortedSet3() {
Student stu1 = new Student(1, "Little");
Student stu2 = new Student(2, "Cyntin");
Student stu3 = new Student(3, "Tony");
Student stu4 = new Student(4, "Gemini");
SortedSet set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if (o1 instanceof Student
&& o2 instanceof Student) {
Student s1 = (Student) o1;
Student s2 = (Student) o2;
return s1.getName().compareTo(s2.getName());
}
return 0;
}
});
set.add(stu1);
set.add(stu3);
set.add(stu4);
set.add(stu2);
set.add(stu4);
set.add(new Student(12, "Little"));
System.out.println(set);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有