Hamkuu Shaw Hamkuu Shaw - 1 year ago 79
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?

Answer Source

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) 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download