接口:
package cn.sxt.interface2;
public interface Comparator1 {
int compare(Object obj1, Object obj2);
}
三种比较方式:
package cn.sxt.interface2;
public class StuAgeComp implements Comparator1 {
//比较年龄
@Override
public int compare(Object obj1, Object obj2) {
// TODO Auto-generated method stub
Student s1 = (Student)obj1;
Student s2 = (Student)obj2;
return s1.getAge() - s2.getAge();
}
}
package cn.sxt.interface2;
public class StuScoComp implements Comparator1 {
//比较分数
@Override
public int compare(Object obj1, Object obj2) {
// TODO Auto-generated method stub
Student s1 = (Student)obj1;
Student s2 = (Student)obj2;
if(s1.getScore() > s2.getScore()){
return 1;
}else if(s1.getScore() > s2.getScore()){
return -1;
}else{
return 0;
}
}
}
package cn.sxt.interface2;
public class StuNamComp implements Comparator1 {
//比较姓名
@Override
public int compare(Object obj1, Object obj2) {
// TODO Auto-generated method stub
Student s1 = (Student)obj1;
Student s2 = (Student)obj2;
return s1.getName().compareTo(s2.getName());
}
}
冒泡排序:
package cn.sxt.interface2;
public class ArrayUtil {
public static void sort(Object[] arr, Comparator1 comp){//comp = new StuNamComp;
boolean flag = false;
Object temp;
for(int i = 0; i < arr.length - 1; i++){
flag = false;
for(int j = 0; j < arr.length - 1 - i; j++){
if(comp.compare(arr[j], arr[j+1]) > 0){//arr[j] > arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
flag = true;
}
}
if(flag == false){
break;
}
}
}
}
学生类:
package cn.sxt.interface2;
public class Student {
String name;
int age;
int score;
public Student(String name, int age, int score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
public void setScore(int score) {
this.score = score;
}
}
主方法:
package cn.sxt.interface2;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Student[] ss = new Student[4];
ss[0] = new Student("lao1", 34, 89);
ss[1] = new Student("lao2", 18, 10);
ss[2] = new Student("lao3", 20, 100);
ss[3] = new Student("lao4", 16, 40);
//创建比较器
//StuScoComp ssc = new StuScoComp();
StuNamComp snc = new StuNamComp();
//StuAgeComp sac = new StuAgeComp();
//将比较器作为参数传进去
ArrayUtil.sort(ss, snc);
for (Student student : ss) {
System.out.println(student.toString());
}
}
}