javagenericsparameterized

Java two-way parameterized class


Is it possible to do this in java without problems? My IDE highlights my code as "Raw use of parameterized class 'Etat' " and "Unchecked call to 'add(E)' as a member of raw type 'java.util.ArrayList'" My code :

public abstract class Etat<T extends Transition> {}
public abstract class Transition<E extends Etat> {}

Solution

  • Might you be looking for:

    class Etat<E extends Etat<E, T>, T extends Transition<E, T>>  {}
    class Transition<E extends Etat<E, T>, T extends Transition<E, T>> {} 
    

    Then, you can do:

    class MonEtat extends Etat<MonEtat, MaTransition> {}
    class MaTransition extends Transition<MonEtat, MaTransition> {}
    

    allowing the two types to know each other through their type parameter. For instance, if you declare:

    class Etat<E extends Etat<E, T>, T extends Transition<E, T>> {
        abstract E apply(T transition);
    }
    

    You can then be assured that

    MonEtat e = ...;
    e = e.apply(new MaTransition()); // compiles, and knows that MonEtat is returned