1

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?

2 Answers 2

10

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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) {
   ...
}

1 Comment

E extends Comparable<E>. Or, actually, what Elliott Frisch already got. :-P

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.