Take the 2-minute tour ×

I'm trying to write a method to compare two arrays in Java without using .equals().

After comparing the size/length of the arrays, I want to sort them (assuming they are the same size), but I don't know what data type is being stored in each array. How can I figure this out to perform a .sort()?

It's occurring to me that I can possibly do a deepToString() and not worry about actual type since I'm only comparing the arrays here.

if(array1.length = array2.length)
    //figure out array type to perform sorts???
        if(array1[i] != array2[i])
            return false;
        if(i = array1.size() - 1)
            return true;
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted


That's a difficult question:

  • You could get the type of the first element of the array and look at its type; e.g.

    Class type = array[0].getClass();

    But there's no guarantee that all elements of the array will have the same (most derived) type.

  • You could get the basetype of the array; e.g.

    Class type = array.getClass().getComponentType();

    But the actual type of the elements can be any subtype of that type.


Even if you manage to get the actual type of the elements (and they all have the same type), you are still stuck. Just knowing that type won't (in general) allow you to sort them. To sort the array you need one of the following:

  • The element type must implement the Comparable interface.

  • You must supply a separate Comparator object.

I think that your best bet is to forget about the types and do one of the following:

  • Simply call Arrays.sort(Object[]). This works if the array elements all implement Comparable and the elements are mutually comparable.

  • Implement and use a comparator class. In theory, this could be a "universal" comparator that can order any pair of objects that you are likely to encounter in the array. But a better idea would be to implement multiple comparators and pass the appropriate one to your equality method as a parameter or something.

share|improve this answer
add comment
Class type1 = array1[0].getClass();
Class type2 = array2[0].getClass();
    return false;

But your approach of not using equals() is bad. Without knowing what kind of objects are in the array, using the == (or !=) operator is probably only comparing the addresses of the objects (unless they are primitive types).

Running your function on

array1 = {"a", "b", "c"};
array2 = {"a", "b", "c"};

would return false.

share|improve this answer
add comment

Your Answer


