Search code examples
javagenericsarraylistcomparable

Generic method determining if ArrayList is in order (Java)


I'm trying to write a method that determines if an ArrayList is in ascending order. The ArrayList type could be Integer, String etc. As a Java beginner, I've spent the last several hours getting my head around generics, comparable etc. and this is what I've got so far:

static boolean isOrdered(ArrayList<? extends Comparable<?>> a) {
    for(int i=0; i < a.size()-1; i++) {
        if (a.get(i).compareTo(a.get(i+1)) > 0) return false;
    }
    return true;
}

I get the following compile error:

The method compareTo(capture#11-of ?) in the type Comparable is not applicable for the arguments (capture#12-of ? extends Comparable

From what I gather from reading this I understand that it is because it's not sure if a comparison can be made. However I'm still not sure how to correct this.

I'm still quite new to Java (coming from Python). Would kindly appreciate any advice/insights. Thank you!


Solution

  • The issue is the generics here. The way to solve this is to tell the compiler that all the elements are of the same type, called T:

    static <T extends Comparable<T>> boolean isOrdered(ArrayList<T> list)
      ...
    }
    

    This means that the whole list contains all elements of some type T that supports comparing values to other T values.