Skip to content

Compare elements of two arrays of Object

I am trying to build a generic merge method, part of a mergeSort algorithm but I am stuck on how to deal with the comparison.

This is my code so far:

public static Object[] merge(Object[] left, Object[] right) {
    ArrayList<Object> output = new ArrayList<>(left.length > right.length ? left.length : right.length);

    int leftIndex = 0; 
    int rightIndex = 0;

    while (leftIndex < left.length && rightIndex < right.length) {
        if ( left[leftIndex].compareTo(right[rightIndex]) ) { <-- the problem
        } else {

    //add left over elements
    output.addAll(Arrays.copyOfRange(left, leftIndex, left.length));
    output.addAll(Arrays.copyOfRange(right, rightIndex, right.length));

    return output.toArray();

This doesn’t work though, the Object class doesn’t have any “compare” method.

One idea I had is to pass a Comparable as an argument to the merge method and use it in the condition, though it doesn’t feel to me like the best way to achieve this goal.

Another one that I didn’t manage to make work is something as the following:

public static Object[] merge(Object[]<T implements Comparable> left, 
                             Object[]<implements Comparable> right) {

Essentially trying to state that the elements of the array MUST implement the Comparable interface, though I am not really sure how to do this.

How else can this be done, perhaps in a more elegant way?


If you want to use Comparable you can do

public static <T extends Comparable<T>> T[] merge(T[] left, T[] right) {

or, if you want to use it with classes that don’t implement Comparable, you can supply a Comparator, like

public static <T> T[] merge(T[] left, T[] right, Comparator<? super T> comparator) {

The implementations inside of Arrays.sort do something similar.