Comparator

public class ComparatorTest {
	public static void main(String[] args){
		Car car1 = new Car("Tokyo", 20);
		Car car2 = new Car("LandRover", 50);
		Car car3 = new Car("Ferrari", 100);
		Car car4 = new Car("Porsche", 100);
		Car[] cars = new Car[]{car2, car1, car4, car3};
		Arrays.sort(cars, new ComparatorCar());
		for (Car car : cars) {
			System.out.println(car.getName() + ":" + car.getSpeed()); //car1, car2, car4, car3
		}
	}
}

class Car{
	private int speed;
	private String name;
	
	public Car(String name, int speed) {
		this.name = name;
		this.speed = speed;
	}
	public int getSpeed() {
		return speed;
	}
	public void setSpeed(int speed) {
		this.speed = speed;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
class ComparatorCar implements Comparator{
	@Override
	public int compare(Object car0, Object car1) {
		if(((Car)car0).getSpeed() > ((Car)car1).getSpeed()){
			return 1;
		}else if(((Car)car0).getSpeed() == ((Car)car1).getSpeed()){
			return 0;
		}
		return -1;
	}
}

你可能感兴趣的:(Java)