You can do so with the Comparable interface. Lets assume we have a Class Car, which can be of a certain brand (name in this example)
public class Car implements Comparable<Car> {
private String name;
private String color;
/**
* Names
*/
public enum Name {
FIAT("fiat"), RENAULT("renault"), HONDA("honda");
private final String name;
private Name(final String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
/**
* Colors
*/
public enum Colors {
BLUE("blue"), RED("red"), YELLOW("yellow");
private final String color;
private Colors(final String color) {
this.color = color;
}
public String toString() {
return this.color;
}
}
/**
* Construct car with name and color
* @param name
* @param color
*/
public Car(Name name, Colors color) {
this.name = name.toString();
this.color = color.toString();
}
/**
* return name
* @return
*/
public String getName() {
return this.name;
}
/**
* compare to other car
*/
@Override
public int compareTo(Car car2) {
return this.name.compareTo(car2.getName());
}
}
And the main:
import java.util.Arrays;
public class Main {
//private static List<Car> cars = new ArrayList<Car>();
private static Car[] cars = new Car[3];
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Create cars in array");
cars[0] = new Car(Car.Name.RENAULT, Car.Colors.YELLOW);
cars[1] = new Car(Car.Name.HONDA, Car.Colors.BLUE);
cars[2] = new Car(Car.Name.FIAT, Car.Colors.RED);
// System.out.println("Create cars in arraylist");
// cars.add(new Car(Car.Name.RENAULT, Car.Colors.YELLOW));
// cars.add(new Car(Car.Name.HONDA, Car.Colors.BLUE));
// cars.add(new Car(Car.Name.FIAT, Car.Colors.RED));
System.out.println("Print cars");
for (Car car : cars) {
System.out.println("Car name: "+car.getName());
}
// sort cars, see Car class
Arrays.sort(cars);
System.out.println("Print cars after sort");
for (Car car : cars) {
System.out.println("Car name: "+car.getName());
}
}
}
See the console for output.