对复杂对象数组进行排序

2014-09-14 06:30:01 阅读( 93 )

2470人 收藏本页

标签:Java面试题

代码:

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 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接口

来自IT公司面试手册

下一篇:解释下volatile

上一篇:java程序员面试经典面试题

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题