对复杂对象数组进行排序

匿名网友 匿名网友 发布于: 2015-08-30 00:00:00
阅读 133 收藏 0 点赞 0 评论 0

代码:

import java.util.Arrays;

public class CompareArray {

public void comparableExample() {

// Car对象实现Comparable接口
Car car1 = new Car("Toyota", 2006, 5000);
Car car2 = new Car("BMW", 2007, 5000);
Car car3 = new Car("Chrysler", 2007, 4000);

// 比较
System.out.println("Car 1 equals Car 2: " + car1.compareTo(car2));
System.out.println("Car 1 equals Car 3: " + car1.compareTo(car3));
System.out.println("Car 2 equals Car 3: " + car2.compareTo(car3));
System.out.println();

// 排序
Car[] carArray = new Car[] { car1, car2, car3 };
Arrays.sort(carArray);

// 打印
for (Car car : carArray)
System.out.println(car.toString());
}

// 实现Comparable,按自己要求重写compareTo方法
class Car implements Comparable {

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;
}

// 此例子是根据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 void setMake(String make) {
this.make = make;
}

public void setYear(int year) {
this.year = year;
}

public void setMileage(int mileage) {
this.mileage = mileage;
}

public String getMake() {
return make;
}

public int getYear() {
return year;
}

public int getMileage() {
return mileage;
}

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 static void main(String[] args) {
new CompareArray().comparableExample();
}
}

运行结果:

Car 1 equals Car 2: 0
Car 1 equals Car 3: 1
Car 2 equals Car 3: 1

Make: Chrysler
Year: 2007
Mileage: 4000

Make: Toyota
Year: 2006
Mileage: 5000

Make: BMW
Year: 2007
Mileage: 5000

注:
只要是实现了Comparable接口的都可以通过这样来进行排序

String也是实现了Comparable接口

评论列表
文章目录