//封装一个排序类
package com.lanou.jk;
public interface Sort {
//规则
public int sort(Object obj,Object obj1);
}
class Test {
//接收用户定义的排序规则的类
public Sort s;
public Test(Sort s){
this.s = s;//不写无参数的意味着必须给个s否则不能用
}
public Object[] paixu(Object[] obj){
for (int i = 0; i < obj.length - 1; i++) {
for (int j = 0; j < obj.length - i - 1; j++) {
//判断大小
int result = s.sort(obj[j], obj[j+1]);
if (result > 0) {
Object temp = obj[j];
obj[j] = obj[j+1];
obj[j+1] = temp;
}
//交换
}
}
return obj;
}
}
//用户类
package com.lanou.jk;
import java.util.Arrays;
public class User {
public static void main(String[] args) {
//数据
Cat c = new Cat();
c.age = 12;
c.score = 99;
Cat c1 = new Cat();
c1.age = 4;
c1.score = 55;
Cat c2 = new Cat();
c2.age = 9;
c2.score = 88;
Cat c3 = new Cat();
c3.age = 21;
c3.score = 85;
//创建一个数组
Cat[] arr = {c,c1,c2,c3};
//创建test接收的类
com cm= new com();
Test test = new Test(cm);
//接收排序的结果
Object[] newArr = test.paixu(arr);
//打印输出
System.out.println(Arrays.toString(newArr));
}
}
//Sort接口的实现类
class com implements Sort {
@Override
public int sort(Object obj, Object obj1) {
//强转转换类型
Cat c = (Cat)obj;
Cat c1 = (Cat)obj1;
//利用Sort方法进行比较
if (c.score > c1.score) {
return 1;
}
return -1;
}
}
//数据类
class Cat{
int age;
int score;
@Override
public String toString() {
// TODO Auto-generated method stub
return "年龄 = "+ this.age + "分数"+ this.score;
}
}
网友评论