//封裝一個(gè)排序類(lèi)
package com.lanou.jk;
public interface Sort {
//規(guī)則
public int sort(Object obj,Object obj1);
}
class Test {
//接收用戶(hù)定義的排序規(guī)則的類(lèi)
public Sort s;
public Test(Sort s){
this.s = s;//不寫(xiě)無(wú)參數(shù)的意味著必須給個(gè)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;
}
}
//用戶(hù)類(lèi)
package com.lanou.jk;
import java.util.Arrays;
public class User {
public static void main(String[] args) {
//數(shù)據(jù)
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;
//創(chuàng)建一個(gè)數(shù)組
Cat[] arr = {c,c1,c2,c3};
//創(chuàng)建test接收的類(lèi)
com cm= new com();
Test test = new Test(cm);
//接收排序的結(jié)果
Object[] newArr = test.paixu(arr);
//打印輸出
System.out.println(Arrays.toString(newArr));
}
}
//Sort接口的實(shí)現(xiàn)類(lèi)
class com implements Sort {
@Override
public int sort(Object obj, Object obj1) {
//強(qiáng)轉(zhuǎn)轉(zhuǎn)換類(lèi)型
Cat c = (Cat)obj;
Cat c1 = (Cat)obj1;
//利用Sort方法進(jìn)行比較
if (c.score > c1.score) {
return 1;
}
return -1;
}
}
//數(shù)據(jù)類(lèi)
class Cat{
int age;
int score;
@Override
public String toString() {
// TODO Auto-generated method stub
return "年齡 = "+ this.age + "分?jǐn)?shù)"+ this.score;
}
}