简体   繁体   中英

How to implement a List Class that only accepts Comparable Objects

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?

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>> {

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)...
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM