Skip to content

Instantly share code, notes, and snippets.

@SiAust
Last active May 7, 2020 14:09
Show Gist options
  • Save SiAust/eacdf33ac391688a79a4ea4a3f447eb5 to your computer and use it in GitHub Desktop.
Save SiAust/eacdf33ac391688a79a4ea4a3f447eb5 to your computer and use it in GitHub Desktop.
Exampale of using Comparable<> interface to sort objects.
class CarsTest {
public static void main(String[] args) {
Ferrari ferrari = new Ferrari(200);
Jaguar jaguar = new Jaguar(190);
Lotus lotus = new Lotus(170);
Lamborghini lamborghini = new Lamborghini(210);
ArrayList<FastCar> fastCars = new ArrayList<>();
fastCars.add(ferrari);
fastCars.add(jaguar);
fastCars.add(lotus);
fastCars.add(lamborghini);
System.out.println(fastCars.toString());
Collections.sort(fastCars);
System.out.println(fastCars.toString());
}
}
/*
* This class is the super class for fast cars. It implements Comparable interface, when implementing compareTo() the return value defines sort
* order for a collection of FastCar's
* */
class FastCar implements Comparable<FastCar> {
int topSpeed;
String name;
public FastCar(String name, int topSpeed) {
this.name = name;
this.topSpeed = topSpeed;
}
public int getTopSpeed() {
return topSpeed;
}
@Override
public String toString() {
return name.toUpperCase() + " SPEED: " + topSpeed;
}
// Returns 1 if this object is > car, 0 if this object == car or -1 if this object < car.
@Override
public int compareTo(FastCar car) {
return Integer.compare(this.topSpeed, car.topSpeed);
}
}
class Ferrari extends FastCar {
public Ferrari(int topSpeed) {
super("Ferrari" , topSpeed);
}
}
class Lotus extends FastCar {
public Lotus(int topSpeed) {
super("Lotus", topSpeed);
}
}
class Lamborghini extends FastCar {
public Lamborghini(int topSpeed) {
super("Lamborghini", topSpeed);
}
}
class Jaguar extends FastCar {
public Jaguar(int topSpeed) {
super("Jaguar", topSpeed);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment