Import java. util. arrays;
Class car implements comparable {// class car implements the comparable interface and rewrite compareto () as required ()
Private string make;
Private int year;
Private int mileage;
Public Car (string make, int year, int mileage ){
This. Make = make;
This. Year = year;
This. mileage = mileage;
}
// This example compares Objects Based on the mileage.
Public int compareto (Object OBJ ){
If (OBJ instanceof car ){
Car car = (CAR) OBJ;
If (this. mileage> Car. getmileage ())
Return 1;
Else if (this. mileage <car. getmileage ())
Return-1;
}
Return 0;
}
Public String GetMake (){
Return make;
}
Public void setmake (string make ){
This. Make = make;
}
Public int getyear (){
Return year;
}
Public void setyear (INT year ){
This. Year = year;
}
Public int getmileage (){
Return mileage;
}
Public void setmileage (INT mileage ){
This. mileage = mileage;
}
@ Override
Public String tostring (){
Stringbuffer buffer = new stringbuffer ();
Buffer. append ("Make:" + make + "\ n ");
Buffer. append ("year:" + year + "\ n ");
Buffer. append ("mileage:" + mileage + "\ n ");
Return buffer. tostring ();
}
}
Public class comparearray {
Public void comparableexample (){
// The car object implements the comparable interface.
Car car1 = new car ("Audi", 2007,5000 );
Car car2 = new car ("BMW", 2007,5000 );
Car car3 = new car ("Chrysler", 2007,4000 );
System. Out. println ("car1 equals car2:" + car1.compareto (car2 ));
System. Out. println ("car1 equals car3:" + car1.compareto (car3 ));
System. Out. println ("car2 equals car3:" + car2.compareto (car3 ));
System. Out. println ();
// Sort
Car [] cararray = new car [] {car1, car2, car3 };
Arrays. Sort (cararray );
// Print
For (car: cararray)
System. Out. println (car. tostring ());
}
Public static void main (string ARGs []) {
New comparearray (). comparableexample ();
}
}
Output result:
Car1 equals car2: 0
Car1 equals car3: 1
Car2 equals car3: 1
Make: Chrysler
Annual: 2007
Mileage: 4000
Make: AUDI
Annual: 2006
Mileage: 5000
Make: BMW
Annual: 2007
Mileage: 5000
Note: As long as the comparable interface is implemented, you can sort it in this way. String also implements the comparable Interface