对于一些自定义类,我们无法避免对sort的重写
第一种方法
class windows implements Comparable < windows> {
public int x1, y1, x2, y2, level;
public void init ( int a, int b, int c, int d, int e) {
this . x1= a;
this . y1= b;
this . x2= c;
this . y2= d;
this . level= e;
}
@Override
public int compareTo ( windows arg0) {
return this . level - arg0. level;
}
}
Scanner in = new Scanner ( System. in) ;
int n = in. nextInt ( ) ;
windows[ ] win = new windows [ n] ;
for ( int i= 0 ; i< n; i++ )
{
int x1= in. nextInt ( ) ;
int y1= in. nextInt ( ) ;
int x2= in. nextInt ( ) ;
int y2= in. nextInt ( ) ;
int level = in. nextInt ( ) ;
win[ i] = new windows ( ) ;
win[ i] . init ( x1, y1, x2, y2, level) ;
}
Arrays. sort ( win) ;
此代码实现了对于windows类的存储数组win实现了sort
第二种方法
class windows {
public int x1, y1, x2, y2, level;
public void init ( int a, int b, int c, int d, int e) {
this . x1= a;
this . y1= b;
this . x2= c;
this . y2= d;
this . level= e;
}
}
Scanner in = new Scanner ( System. in) ;
int n = in. nextInt ( ) ;
windows[ ] win = new windows [ n] ;
for ( int i= 0 ; i< n; i++ )
{
int x1= in. nextInt ( ) ;
int y1= in. nextInt ( ) ;
int x2= in. nextInt ( ) ;
int y2= in. nextInt ( ) ;
int level = in. nextInt ( ) ;
win[ i] = new windows ( ) ;
win[ i] . init ( x1, y1, x2, y2, level) ;
}
Arrays. sort ( win, new Comparator < windows> ( ) {
public int compare ( windows arg0, windows arg1) {
return arg0. level - arg1. level;
}
} ) ;