Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics: Bound mismatch

Tags:

java

generics

I have a generic class with this definition:

public class AcoProblemSolver<C, E extends Environment, A extends AntColony<E, Ant<C, E>>> {

Where AntColony goes this way:

public abstract class AntColony<E extends Environment, A extends Ant<?, E>> {

And Ant goes like this:

public abstract class Ant<C, E extends Environment> {

I was hoping to extend AntColony in this fashion:

public class FlowShopProblemSolver extends
    AcoProblemSolver<Integer, FlowShopEnvironment, FlowShopAntColony> {

But Eclipse is showing an error on the FlowShopAntColony parameter class:

Bound mismatch: The type FlowShopAntColony is not a valid substitute for the bounded parameter <A extends AntColony<E,Ant<C,E>>> of the type AcoProblemSolver<C,E,A>

Which confuses me, since FlowShopAntColony is defined this way:

public class FlowShopAntColony extends
    AntColony<FlowShopEnvironment, AntForFlowShop> {

And AntForFlowShop goes like this:

public class AntForFlowShop extends Ant<Integer, FlowShopEnvironment> {

Why isn't FlowShopAntColony accepted as a valid parameter?

like image 728
Carlos Gavidia-Calderon Avatar asked Jul 15 '15 23:07

Carlos Gavidia-Calderon


People also ask

How are bounds used with generics?

Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.

How to declare Java generic bounded type parameter?

To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).

What is bounds in Java?

A bound is a constraint on the type of a type parameter. Bounds use the extends keyword and some new syntax to limit the parameter types that may be applied to a generic type. In the case of a generic class, the bounds simply limit the type that may be supplied to instantiate it.


1 Answers

A extends AntColony<E, Ant<C, E>>

The third parameter of AcoProblemSolver has the restriction extends AntColony<E, Ant<C, E>>. The second parameter of AntColony must be exactly Ant<C, E> and you're trying to pass a subclass of Ant. Try:

A extends AntColony<E, ? extends Ant<C, E>>

You may want other similar ? extends clauses elsewhere.

like image 98
John Kugelman Avatar answered Nov 02 '22 15:11

John Kugelman