0

I am making an implementation of a generic ArrayList class that will follow the given elements natural ordering. I assume there is some way to do this, similar to how TreeSet follows the given elements' natural ordering.

When I use the .compareTo method call on the objects stored within, there is an error that says "Cannot resolve method 'compareTo' in 'E'". How do I tell the compiler that the Object E should only be classes that do implement the comparable interface?

Right now, the relevant code looks like this:

public class SortedList<E> {
    ...
    public int indexOf(E value) {
        ...
        else if (value.compareTo(this.get(minIndex)) > 1)...
    }
}

This post was close to helping: Cannot find compareTo when receiving comparable Object[] but its for one specific static method, while I need the objects for the whole class to be Comparable, and the same addition does not seem to work for the class header.

Is there something I can add to the class header that performs a similar function?

3 Answers 3

3

Specify it like this. This bounded type allows both E and subtypes of E to be compared.

public class SortedList<E extends Comparable<? super E>> {
   
    public int indexOf(E value) {
        ...
        else if (value.compareTo(this.get(minIndex)) > 1)...
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I really thought I tried that haha, but it works like a charm. Thanks! I'll mark as accepted when I can.
3

You have to mandate that your type parameter is comparable to itself (so it has natural ordering). You can do this by bounding the parameter.

public class SortedList<E extends Comparable<E>> {

Comments

1

The multiple inheritance in Java is very rudimentary but something does exist: a class can implement multiple interfaces. Hence a collection can be declared the way

ArrayList<Comparable<?>> list = new ArrayList<>();

and then you can only add various classes that implement Comparable to it without bothering with the type hierarchy.

However while implementing Comparable this way does mean there is a method int compareTo(Object other), the internal implementation of this method most often includes type cast and would not accept arbitrary input.

Modern Java suggest using Comparable<ToSomething> instead, restricting your Comparables to the narrower category. This ToSomething also does not need to be the name of your class, can be another marker interface.

Comments

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.