Hamkuu Shaw Hamkuu Shaw - 4 months ago 9
Java Question

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?


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)