【发布时间】: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....的叶子。
我希望有人得到它并可以提供帮助。
【问题讨论】:
-
泛型有时可能有点让人费解。查看 Angelika Langer 以获得关于这一切如何运作的完整描述。在您的具体情况下:angelikalanger.com/GenericsFAQ/FAQSections/… System
标签: java generics methods recursion arguments