Search code examples
javasortingarraylistmergecomparable

Is it possible to have a method that takes a generic Comparable?


I'm implementing a merge sort algorithm in Java for school.

It should be able to take any object that is comparable.

I created a static mergeSort(ArrayList input) method but apparently I cannot cast ArrayList or ArrayList into ArrayList even though they both implement comparable.

How can I represent an ArrayList of Comparable data ?


Solution

  • Use generics. Something like public static <T extends Comparable<T>> ArrayList<T> mergeSort(ArrayList<T> list) {...

    Then you can use T as a type. Like T a = list.get(0); and you can do (a.compareTo(b)).