About error using Java generics: “type parameter S is not within its bound”

前端 未结 3 994
傲寒
傲寒 2020-12-20 14:06

I am writing some classes using Generics but I can\'t find a solution for the class SolutionsSubset and so I a getting the error \"type parameter S is not within its bound\"

3条回答
  •  爱一瞬间的悲伤
    2020-12-20 14:40

    In order to be used as the type argument in MathSubset, SolutionsSubsets S must extend Comparable. As a compilable example:

    import java.util.TreeSet;
    
    interface Subset>
         extends Comparable> { }
    
    class MathSubset>
        extends TreeSet
        implements Subset
    {
        public int compareTo(Subset other) { throw new Error(); }
    }
    
    interface Solution> { }
    
    interface Solutions> extends Iterable { }
    
    class SolutionsSubset & Comparable>
        extends MathSubset
        implements Solutions
    { }
    

    A few comments: This is very abstract example, and so not easy to think about. Laying out the code so you don't need to scroll is good. There's an awful lot of inheritance going on here, perhaps compose rather than, say, extending TreeSet. It's difficult to distinguish between the identifiers Solutions and Solution.

提交回复
热议问题