重寫compareTo方法,按不同方式實現排序,小程式
1:寫一個Cart類,並實現Comparable介面,同時重寫compareTo方法。
package com.paixu;
import com.paixu.Car;public class Car implements Comparable<Object>{
public final static int STRNO=1;
public final static int STRNAME=2;
public final static int PRICE=3;
public final static int SALE=4;
public static int SortFiled=STRNO;
private long strNo;
private String strName;
private int price;
private int sale;
public long getStrNo() {
return strNo;
}
public void setStrNo(long strNo) {
this.strNo = strNo;
}
public String getStrName() {
return strName;
}
public void setStrName(String strName) {
this.strName = strName;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getSale() {
return sale;
}
public void setSale(int sale) {
this.sale = sale;
}
public Car(long strNo, String strName, int price, int sale) {
super();
this.strNo = strNo;
this.strName = strName;
this.price = price;
this.sale = sale;
}
//按價格
public int compareTo(Object o)
{
Car car = (Car)o;
switch(SortFiled)
{
case STRNO:
return (int) (this.strNo-car.strNo);
case STRNAME:
return this.strName.compareTo(car.strName);
case PRICE:
return this.price-car.price;
case SALE:
return this.sale-car.sale;
default:
break;
}
return 0;
}
}
2:寫一個測試類,Test根據不同屬性 對不同Cart物件排序
package com.paixu;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
/**
* @param args
*/
public static void change()
{
Scanner scanner = new Scanner(System.in);
int n;
System.out.println("1:按編號排序2:按價格排序3:按牌子排序4:按銷售量排序");
System.out.println("請選擇:");
n = scanner.nextInt();
switch(n)
{
case 1:
Car.SortFiled = Car.STRNO;
comm();
break;
case 2:
Car.SortFiled = Car.PRICE;
comm();
break;
case 3:
Car.SortFiled = Car.STRNAME;
comm();
break;
case 4:
Car.SortFiled = Car.SALE;
comm();
break;
default:
break;
}
}
public void start()
{
System.out.println("-------------------歡迎進入汽車排序系統--------------------");
change();
}
public static void comm()
{
Car car1 = new Car(1001l,"aodi",230000,330);
Car car2 = new Car(1002l,"xiandai",150000,900);
Car car3 = new Car(1003l,"dazhong",130000,450);
Car car4 = new Car(1004l,"xiaokang",73000,740);
Car car5 = new Car(1005l,"baoma",690000,30);
Car []cars = {car1,car2,car3,car4,car5};
Arrays.sort(cars);
for(Car car:cars)
{
System.out.println("編號:"+car.getStrNo()+"\t|"+"品牌:"+car.getStrName()+"\t|"+"價格:"+car.getPrice()+"\t|"+"銷售:"+car.getSale());
}
}
public static void main(String[] args) {
Test t = new Test();
t.start();
}
}