It would be much simpler to use custom comparators:
To sort by name
:
Arrays.sort(carArray, Comparator.comparing(Car::name));
To sort by colour
:
Arrays.sort(carArray, Comparator.comparing(Car::colour));
So you could modify getSortedArray()
:
public static Car[] getSortedArray(Car[] carArray, Comparator<Car> comparator) {
Car[] sorted = carArray.clone()
Arrays.sort(sorted, comparator);
return sorted;
}
And call it like this:
Car[] sorted = getSortedArray(carArray, Comparator.comparing(Car::name));
Edit:
If you use a language version that does not support these features, you can create the comparators by explicitly creating a nested class that implements the Comparator
interface.
This, for example, is a singleton Comparator
that compares Car
instances by name
:
static enum ByName implements Comparator<Car> {
INSTANCE;
@Override
public int compare(Car c1, Car c2) {
return c1.name().compareTo(c2.name());
}
}
Then call:
Car[] sorted = getSortedArray(carArray, ByName.INSTANCE);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…