3.15---对引用变量按用户要求的条件排序

接口:

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());
}
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值