简体   繁体   中英

How to use Comparable<T>?

I have the following interface

public interface Identifiable {

    public Comparable<?> getIdentifier();

}

And an implementing class

public class Agreement implements Identifiable {

    private Long id;

    public Comparable<Long> getIdentifier() {
        return id;
    }
}

EDIT: Note that there may be other implementations with different types of identifiers.
Now I would like to, yes, compare the comparables:

// Agreement a;
// Agreement b;
...
if (a.getIdentifier().compareTo(b.getIdentifier()) {
...

But the compareTo gives me the following compiler error:

The method compareTo(Long) in the type Comparable<Long> is not applicable for the arguments (Comparable<Long>)

How is this interface supposed to be used with Generics?

Comparable<T> is meant to be used as an upper bound for a generic parameter:

public interface Identifiable<T extends Comparable<T>> {    
    public T getIdentifier();
}

public class Agreement implements Identifiable<Long> {

    private final Long id;

    public Long getIdentifier() {
        return id;
    }
}

This forces the return type to be a T , not just something that can be compared to a T .


Your code is inherently unsafe.
To understand why, consider the following code:

class Funny implements Comparable<Long> { ... }
class Funnier implements Identifiable {
    public Comparable<Long> getIdentifier() {
        return new Funny();
    }
}

Identifiable<Funny> funnier;
funnier.getIdentifier().compareTo(funnier.getIdentifier());
// You just tried to pass a Funny to compareTo(Long)

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