gpt4 book ai didi

java - 如何调用集合中保证存在的泛型类型的方法?

转载 作者:行者123 更新时间:2023-11-30 04:53:09 26 4
gpt4 key购买 nike

我使用泛型已经有一段时间了,但只是以一种简单直接的方式。

现在我想这样做,我一直在阅读和尝试很多东西,例如使用接口(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com