Java泛型错误:不适用于参数
所以第一次泛型,我的任务是制作一个由方块组成的地牢(游戏世界),这些方块(实际上是立方体)有很多类型,但这并不重要 所以我有一个Java泛型错误:不适用于参数,java,generics,methods,recursion,arguments,Java,Generics,Methods,Recursion,Arguments,所以第一次泛型,我的任务是制作一个由方块组成的地牢(游戏世界),这些方块(实际上是立方体)有很多类型,但这并不重要 所以我有一个composedundgeon类,这个类代表一个由其他地牢建造的地牢,它没有自己的方块,但是包含了subdengeon类的其他孩子。这样,我得到了一个树状结构,根ComposedDungeon,叶子不能有自己的叶子,除非它们也是ComposedDungeon 第一个(超级级) 第二个: protected abstract Dimension getDimensionO
composedundgeon
类,这个类代表一个由其他地牢建造的地牢,它没有自己的方块,但是包含了subdengeon
类的其他孩子。这样,我得到了一个树状结构,根ComposedDungeon
,叶子不能有自己的叶子,除非它们也是ComposedDungeon
第一个(超级级)
第二个:
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;
}
公共类ComposedDungeon扩展{
/**
*返回给定正方形的尺寸。
*
*@param广场
*所需尺寸的正方形。
*@返回包含此正方形的维度。
*/
保护尺寸getDimensionOf(E方形){
对于(subvengeon我不相信你可以像那样继承(
),它需要在调用之外:扩展了一些东西。请像这样尝试:
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;
}
}
public类俯冲
{
受保护的抽象尺寸getDimension(E平方);
}
公共类ComposedDungeon扩展到Dumpngeon
{
受保护尺寸getDimension(E方形)
{
维度;
//把你的东西放在这里。
返回维度;
}
}
我相信问题出在ComposedDungeon的for循环#getDimensionOf(E)方法中
for(subvengeon我不能在不了解更多代码的情况下最终回答这个问题,但是
强制执行getDimension
方法的参数必须与类的泛型类型匹配背后的原因是什么?只有getDimension(矩形)
而不是getDimension(正方形)
才能调用ComposedDungeon
有意义吗
至少从您在示例中调用它的方式来看,似乎您真的希望对任何与基类型匹配的对象调用它-因此,我将更改subwngeon
中的原始方法以使用基类型-
public abstract class Subdungeon<E extends Square>
{
...
protected abstract Dimension getDimensionOf(Square square);
...
}
公共抽象类
{
...
受保护的抽象尺寸getDimensionOf(正方形);
...
}
并将ComposedDungeon
更改为匹配。泛型有时会让人有点想入非非。请查看Angelika Langer,了解其工作原理的完整描述。在您的特定情况下:系统
for(Subdungeon<? extends E> dungeon : getAllSubdungeons()){
for(Subdungeon<E> dungeon : getAllSubdungeons()){
public abstract class Subdungeon<E extends Square>
{
...
protected abstract Dimension getDimensionOf(Square square);
...
}