1

So I have a list of objects, specifically a list of vehicles, that contains cars, motos and bicicles. Each one of this objects has different atributes (car and moto have max velocity while bicicle doesn´t for instance.)

Moto Bicicle and Car are subclasses of Vehicle and Vehicle implements the interface Comparable.

They do have on thing in common, the year when they were made and that's how I wanted to sort my array, using that specific attribute. By default java is sorting based on another attribute the objects have in common which is "color".

This is the code used to sort the arrays.(It has to be this one)

public static <T> void sortArray(Comparable<T>[] a) {
        Arrays.sort(a);
}

Is there a way to select the attribute which I would like to use to sort the list? Thanks for the help in advance.

3
  • For your text, I think that Cars, Motos and Bicicles are subclasses of Vehicle and that Vehicle implements the interface Comparable. This last point implies that Vehicle has a method compareTo. Change that method to use "year" instead of "color". Commented Apr 14, 2016 at 18:03
  • docs.oracle.com/javase/7/docs/api/java/util/… Commented Apr 14, 2016 at 18:03
  • Following this link in point 3, you can find an example of what I mean in my previous comment mkyong.com/java/… Commented Apr 14, 2016 at 18:15

2 Answers 2

2

By default Arrays.sort sorts according to the Comparable natural ordering of its elements. If you want to change it, use Arrays.sort(T[] a, Comparator<? super T> c) instead, it allows to define your own comparator.

http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(T[], java.util.Comparator)

Sign up to request clarification or add additional context in comments.

1 Comment

Oh it worked just fine ^^ Thanks a lot :D It actually makes sense now xD. Thanks.
1

You can implement an own comparator and pass it to Arrays.sort(array, comparator). Using lambdas or method handles this is easy:

Vehicle[] v = ...
Arrays.sort(v, (v1,v2) -> v1.getYear() - v2.getYear());

or

Arrays.sort(v, Comparator.comparing(Vehicle::getYear));

Based on that you can write a generic function which sorts an array by a specific attribute:

public static <T, U extends Comparable<? super U>> void sortArray(T[] a, 
    Function<? super T, ? extends U> attribute) {
    Arrays.sort(a, Comparator.comparing(attribute));
}   

and use it with

sortArray(v, Vehicle::getYear);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.