Hiro Shaw
Hiro Shaw

Reputation: 395

Generic Array Comparison in Java

I had a small program using generic method for dealing with array in Java:

public class GenericMethodTest {
    // generic method                         
    public static <E> void inspectArray(E[] inputArray) {
        for (int i = 1; i < inputArray.length; i++) {
            int tmp = inputArray[i-1].compareTo(inputArray[i]);
            //unrelated lines are neglected                
        }
    }

    public static void main(String args[]) {
        // Create arrays of Integer, Double and Character
        Integer[] intArray = { 2, 2, 3, 4, 2 };
        Character[] charArray = { 'A', 'A', 'G', 'A', 'A' };
        inspectArray( intArray  ); // pass an Integer array
        inspectArray( charArray ); // pass a Character array
    } 
}

However, I got an error message saying:

"The method compareTo(E) is undefined for the type E"

How can I fix this?

Upvotes: 1

Views: 2210

Answers (2)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36431

You need to specify that the type E has a compareTo method, that is the contract of the interface Comparable<T>, then this could be written as:

public static <E extends Comparable<E>> void inspectArray( E[] inputArray) {
   ...
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201467

You need to ensure that E is Comparable. The correct method signature would be

public static <E extends Comparable<? super E>> void inspectArray(E[] inputArray) 

Upvotes: 10

Related Questions