Java 如何在模板类中实例化T类型
我有一个抽象类Java 如何在模板类中实例化T类型,java,oop,Java,Oop,我有一个抽象类抽象类MathFunc,用于在其特定类中实现数学函数Rastrigin、Griewangk和Rosenbrock最终类Rastrigin扩展MathFunc,最终类Griewangk扩展MathFunc和最终类Rosenbrock扩展MatjFunc 到目前为止,这种类的层次结构以及它们的定义方式工作得完美无缺,因此我认为没有必要在这方面寻求改进 现在我必须实现另一个类Generation,其中将包含一些ArrayLists,但问题是我需要为上面描述的每个数学函数实现一个Gener
抽象类MathFunc
,用于在其特定类中实现数学函数Rastrigin、Griewangk和Rosenbrock最终类Rastrigin扩展MathFunc
,最终类Griewangk扩展MathFunc
和最终类Rosenbrock扩展MatjFunc
到目前为止,这种类的层次结构以及它们的定义方式工作得完美无缺,因此我认为没有必要在这方面寻求改进
现在我必须实现另一个类Generation
,其中将包含一些ArrayLists
,但问题是我需要为上面描述的每个数学函数实现一个Generation。
所以我需要像这样的东西:
ArrayList<Rastrigin> rast = new ArrayList<>();
ArrayList<Griewangk> grie = new ArrayList<>();
ArrayList<Rosenbrock> rose = new ArrayList<>();
ArrayList rast=new ArrayList();
ArrayList grie=新的ArrayList();
ArrayList rose=新的ArrayList();
在这些列表中,我有一些需要实例化的Rastrigin/Griewangk/Rosenbrock对象
<>我从C++的过去的项目中知道,我可以使用模板来指定一个通用的数据类型,我认为这是我的解决方案。到目前为止,我的实现如下所示:
public class Generation <MathFunc> {
private final ArrayList<MathFunc> pop = new ArrayList<>();
private final ArrayList<MathFunc> nextpop = new ArrayList<>();
private final ArrayList<MathFunc> Crossover = new ArrayList<>();
Generation(MathFunc tp)
{
for(int i = 0; i < PopSize; i++)
{
pop.add(tp);
}
}
}
公共类生成{
private final ArrayList pop=new ArrayList();
private final ArrayList nextop=new ArrayList();
私有最终ArrayList交叉=新ArrayList();
生成(MathFunc tp)
{
对于(int i=0;i
但问题是:我可以使用抽象类来实例化依赖它的对象吗?还有别的办法吗?我对模板的使用很困惑
但是对我来说,生成(Mathfunc-tp)似乎有点奇怪,因为抽象类是不可实例化的
p.S.似乎是一个可能的解决方案,但我不确定它或它实际上是如何工作的。如果您想重用同一个
MathFunc
实例,我看不到您的代码中有任何重大缺陷(除了Generation
的一般定义应为Generation之外,是否要使用同一MathFunc
子类的多个实例?还是添加同一实例(tp
)是正确的多次添加到列表中?@Thomas我想在第二代中添加10个Rastrigin类型的对象或10个Rosenbrock类型的对象等,但我不知道如何实例化它们。@Thomas请查看对您答案的评论,并提供一些关于工厂模式的解释。我非常喜欢这个答案,非常感谢您尝试这两种方法解决方案!我真的忘记了工厂模式。公共接口MathFuncFactory(){T createFunc();}似乎有问题。
出现错误。请告诉我如何修复它。
public class Generation <T extends MathFunc> {
private final ArrayList<T> pop = new ArrayList<>();
private final ArrayList<T> nextpop = new ArrayList<>();
private final ArrayList<T> Crossover = new ArrayList<>();
Generation(T tp) {
for(int i = 0; i < PopSize; i++) {
pop.add(tp);
}
}
}
Generation<Rastrigin> rastriginGen = new Generation<>(new Rastrigin());
Generation<Griewangk> griewangkGen = new Generation<>(new Griewangk());
Generation<Rosenbrock> rosenbrockGen = new Generation<>(new Rosenbrock());
interface MathFuncFuncFactory<T extends MathFunc> {
T createFunc();
}
Generation(MathFuncFactory<T> factory) {
for(int i = 0; i < PopSize; i++) {
pop.add(factory.createFunc());
}
}
Generation<Rastrigin> rastriginGen = new Generation<>(new RastriginFactory());