Inheritance Generic Comparable

Trying to create a superclass that guarantees that all subclasses are inherently Comparable.

/**
 * A base class implementing Comparable with itself by delegation.
 * @param <T> - The type being wrapped.
 */
static class Distinct<T extends Comparable<T>> implements Comparable<Distinct<T>> {
    final T it;
    public Distinct(T it) {
        this.it = it;
    }
    @Override
    public int compareTo(Distinct<T> o) {
        return it.compareTo(o.it);
    }
}
/**
 * A set of distinct items.
 *
 * @param <T>
 */
static class ThingHolder<T extends Comparable<T>> {
    final Set<T> things;
    public ThingHolder() {
        this.things = new TreeSet<>();
    }
}
/**
 * A sample real thing.
 */
static class Thing extends Distinct<String> {
    public Thing(String it) {
        super(it);
    }
}
// This doesn't work - Why?
final ThingHolder<Thing> yz = new ThingHolder<>();

The error I am reading is:

com/oldcurmudgeon/test/Test.java:[70,22] error: type argument Thing is not within bounds of type-variable T
  where T is a type-variable:
    T extends Comparable<T> declared in class ThingHolder

Why is this not working? It can be done?

+4
source share
4 answers
  • If you pass a type argument Xto ThingHolder, it must be a subtype Comparable<X>(by class declaration ThingHolder).
  • So, if you pass a type Thingto ThingHolder, it must be a subtype Comparable<Thing>. (Performed from the previous statement by replacing Thingwith X.)
  • Thingextends Distinct<String>and therefore implements Comparable<Distinct<String>>(by class declaration Thing).
  • Thing - , Distinct<String> - - , , .

, ThingHolder :

class ThingHolder<T extends Comparable<? super T>> {
    ...
}
+2

.

, API, T , (? super T).

( ? super T) :

/**
 * A set of distinct items.
 *
 * Don't like the <?> in there but a <T> is not accepted.
 *
 * @param <T>
 */
static class ThingHolder<T extends Comparable<? super T>> {

    final Set<T> things = new TreeSet<>();

}

final ThingHolder<Thing> holder = new ThingHolder<>();

.

, ? , , .

+1

Just change the class signature ThingHolderto:

static class ThingHolder<T extends Comparable> {
       ...    
}

those. remove <T>from Comparable, this is not necessary.

0
source

class ThingHolder<T extends Comparable<T>>declares that the thing Tmust be comparable with itself, but is class Thing extends Distinct<String>not.

0
source

Source: https://habr.com/ru/post/1615547/


All Articles