Rafael
Rafael

Reputation: 2443

Creating a generic class where the parameter is an array

I want to create a class that exends Comparator. This comparator will compare two arrays, where the arrays can contain anything that is comparable. Something that would let me do things like this:

comparator.compare(new Integer[] {1,2}, new Integer[] {3,4,5});

the type of the parameters are not necessarily Integer[]. They could be an array of anything.

Is there any way I can create such a class using generics? Or should my comparator receive objects instead. If it must receive objects, how can I check if it is an array and get elements from inside it?

Upvotes: 0

Views: 165

Answers (3)

Mattias Isegran Bergander
Mattias Isegran Bergander

Reputation: 11909

Yes you can, for example like this:

implements Comparator<T[]> {
    @Override
    public int compare(T[] array1, T[] array2) {
        //compare arrays here
        return ...;
    }

or a compare method like this that will infer the type on the calling values:

public static <T> int compare(T[] array1, T[] array2) {

Upvotes: 2

FThompson
FThompson

Reputation: 28697

Your Comparator parameter type should be T[].

Here's an example usage:

public class Test<T> implements java.util.Comparator<T[]> {

    @Override
    public int compare(T[] paramT1, T[] paramT2) {
        return 0;
    }

    public static void main(String[] args) {
        System.out.println(new Test<Integer>().compare(new Integer[] {1,2}, new Integer[] {3,4,5}));
    }

}

Upvotes: 2

Jeffrey
Jeffrey

Reputation: 44808

How about using the array itself as the type parameter to Comparator?

public class ArrayComparator<T extends Comparable<? super T>> implements
        Comparator<T[]> {
    @Override
    public int compare(T[] o1, T[] o2) {
        // TODO
    }
}

Upvotes: 3

Related Questions