62,623
社区成员
发帖
与我相关
我的任务
分享interface Sortable{
int Compare(Sortable s);// 定义一个接口
}
class Sort{ // 定义一个排序类,仅有一个静态的方法
public static void SelectSort(Sortable a[ ]){
int i, j, k;
Sortable temp;
for(i=0;i <a.length-1;i++){ // 选择排序
k=i;
for(j=i+1;j <a.length;j++)
if(a[k].Compare(a[j]) <0) k=j;
temp=a[i]; a[i]=a[k]; a[k]=temp;
}
}
}
// 定义一个学生类
class Student implements Sortable{
private int score;
Student(int x){
score=x;
}
// 实现接口Sortable中的方法
public int Compare(Sortable s){
Student st=(Student)s; // 类型强制转换
return score-st.score;
}
public String toString( ){
return "score="+score;
}
}
// 矩形类也实现了接口
class Rectangle implements Sortable{
private int length,width;
Rectangle(int x,int y){
length=x; width=y;
}
int area( ){
return length*width;
}
// 实现接口
public int Compare(Sortable s){
Rectangle rec=(Rectangle)s; // 类型强制转换
return area( )-rec.area( );
}
public String toString( ){
return "area="+area( );
}
}
public class InterfaceTest {
public static void main(String args[ ]) {
Student stud[ ]=new Student[20];
int i;
for( i=0;i <stud.length;i++)
stud[i]=new Student((int)(Math.random( )*100));
Sort.SelectSort(stud); // 排序
for( i=0;i <stud.length;i++)
System.out.println(stud[i].toString( ));
Rectangle R[ ]=new Rectangle[10];
for( i=0;i <R.length;i++)
R[i]=new Rectangle((int)(Math.random( )*10),(int)(Math.random( )*10));
Sort.SelectSort( R ); // 排序
for( i=0;i <R.length;i++)
System.out.println(R[i].toString( ));
}
} class Student implements Sortable{ // 定义一个学生类
private int score;
Student(int x){ score=x; }
// 实现接口Sortable中的方法
public int Compare(Sortable s){
Student st=(Student)s; // 类型强制转换
return score-st.score;
}