作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用泛型已经有一段时间了,但只是以一种简单直接的方式。
现在我想这样做,我一直在阅读和尝试很多东西,例如使用接口(interface)和通配符,但没有成功。我想了解是否有一种有效的方法可以使用 Java 泛型实现此目的,或者我是否误解了泛型的使用方式。
假设我想创建一个通用集合类,一个 ArrayList,并且我想为各种不同类型但重要的是确保实现某种方法的不同类型创建这样的数组列表。然后我希望能够从我的通用数组列表中调用该方法。
下面的代码非常简单,而且显然行不通,我知道这一点。我已经尝试了很多比这更复杂的想法,但是我包含以下代码只是为了总结我想要做的事情,并提供答案的示例。
查看 DemonstrateProblem() 中的代码行...我希望能够调用它,前提是我只会在 TestContainer 中使用实现 StartGame() 方法的类型
public class TestContainer<T> extends ArrayList<T> {
public void DemonstrateProblem() {
// assumes we have populated the collection with 5+ objects...
// the line of code below is ultimately what I would like to acheive
this.get(4).StartGame(); // <-- my goal!
}
}
public abstract class Game () {
public void StartGame() {}
public void EndGame() {}
}
public class HockeyGame extends Game {
// ... overrides here
}
public class BaseballGame extends Game {
// ... overrides here
}
public class BasketballGame extends Game {
// ... overrides here
}
最佳答案
您不需要在 T
上保持容器通用:您可以在 Game
上实例化现有的通用容器,如下所示:
public class TestContainer extends ArrayList<Game> {
public void DemonstrateProblem() {
this.get(4).StartGame(); // <-- should work
}
}
关于java - 如何调用集合中保证存在的泛型类型的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9424754/
我是一名优秀的程序员,十分优秀!