【问题标题】:Java Generics Error: not applicable for the argumentsJava 泛型错误:不适用于参数
【发布时间】:2011-08-29 15:16:15
【问题描述】:

所以第一次使用泛型,我的任务是制作一个由正方形组成的地牢(游戏世界),这些正方形(实际上是立方体)有很多类型,但这并不重要。

所以我有一个ComposedDungeons 类,这个类代表一个由其他地牢构建的地牢,它没有自己的正方形,但包含SubDungeon 类的其他子级。这样我就得到了一个树状结构,其根为ComposedDungeon,而叶子不能有自己的叶子,除非它们也是ComposedDungeons

第一个(超级班)

public abstract class Subdungeon<E extends Square> {
....

问题方法:

protected abstract Dimension getDimensionOf(E square);

第二个:

public class ComposedDungeon<E extends Square> extends Subdungeon<E> {

    /**
 * Return the dimension of the given Square.
 * 

 * @param   square
 *          The square of which the dimension is required.
 * @return  The dimension which contains this square.
 */
protected Dimension getDimensionOf(E square){
    for(Subdungeon<? extends E> dungeon : getAllSubdungeons()){
        Dimension dimension = dungeon.getDimensionOf(square);
        if(dimension != null)
            return dimension.add(getDimensionOfDungeon(dungeon));
    }
    return null;
}

错误 - Subdungeon 不适用于参数 (E)

我不知道如何解决这个问题,我的想法是使方法递归,这样它就会一直搜索,直到找到不是ComposedDungeon....的叶子。

我希望有人得到它并可以提供帮助。

【问题讨论】:

标签: java generics methods recursion arguments


【解决方案1】:

我认为问题出在 ComposedDungeon#getDimensionOf(E) 方法中的 for 循环中。

for(Subdungeon<? extends E> dungeon : getAllSubdungeons()){

...应该是...

for(Subdungeon<E> dungeon : getAllSubdungeons()){

E已经被定义为Square类型的子类,所以不需要加上,事实上是不正确的。

【讨论】:

    【解决方案2】:

    我不相信你可以这样继承 (&lt;something extends somethingElse&gt;) 它需要在调用之外:&lt;something&gt; extends somethingElse

    【讨论】:

      【解决方案3】:

      试试这样:

      public class Subdungeon<E>
      {
          protected abstract Dimension getDimension(E square);
      }
      
      public class ComposedDungeon<E> extends Subdungeon<E>
      {
          protected Dimension getDimension(E square)
          {
              Dimension dimension;
      
              // put your stuff here.
      
              return dimension;
          }
      }
      

      【讨论】:

        【解决方案4】:

        如果不了解代码的更多信息,我无法最终回答这个问题,但是...

        强制getDimension 方法的参数必须与类的泛型类型匹配的原因是什么? ComposedDungeon&lt;Rectangle&gt; 应该只能用getDimension(Rectangle) 而不是getDimension(Square) 调用是否有意义?

        至少你在示例中调用它的方式,看起来你真的想在匹配基本类型的 anything 上调用它 - 所以,我会改变原来的方法Subdungeon 使用基本类型 -

        public abstract class Subdungeon<E extends Square>
        {
            ...
            protected abstract Dimension getDimensionOf(Square square);
            ...
        }
        

        并更改 ComposedDungeon 以匹配。

        【讨论】:

          猜你喜欢
          • 2023-03-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-21
          • 1970-01-01
          • 2016-11-17
          相关资源
          最近更新 更多