1

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!

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see, thank you! I didn't realise I had to define the type after static; I tried that within the parentheses to no (useful) effect
for best results use <T extends Comparable<? super T>>

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.