インタフェースの適用_ソートの実装
2508 ワード
public interface Sort {
//
public int sort(Object obj,Object obj1);
}
class Test {
// ( )
public Sort s;
//
public Test(Sort s) {
this.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++) {
// ( ,,)
// sort , ., int ;
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;
}
}
class Cat {
int age;
int score;
// ,
@Override
public String toString() {
return " =" + this.age + " =" + this.score;
}
}
//Sort
class Com implements Sort {
// ;
@Override
public int sort(Object obj, Object obj1) {
// obj Cat
Cat cat = (Cat)obj;
Cat cat2 = (Cat)obj1;
// cat
if (cat.score > cat2.score) {
return 1;
}
return -1;
}
}
public static void main(String[] args) {
// 4 Cat ;
Cat cat1 = new Cat();
cat1.age = 12;
cat1.score = 13;
Cat cat2 = new Cat();
cat2.age = 13;
cat2.score = 20;
Cat cat3 = new Cat();
cat3.age = 10;
cat3.score = 14;
Cat cat4 = new Cat();
cat4.age = 15;
cat4.score = 23;
// ,, Cat ;
Cat[] arr = {cat1,cat2,cat3,cat4};
//
Com com = new Com();
// con Test
Test test = new Test(com);
// Test . .
Object[] newArr = test.paixu(arr);
//
System.out.println(Arrays.toString(newArr));
}