尝试为遗传算法编写一些通用代码,我有一个抽象类 Genotype,如下所示:
public abstract class Genotype {
private ArrayList<Gene> genotype = new ArrayList<Gene>();
//...
public Genotype(ArrayList<Gene> genotype) {
setGenotype(genotype);
setGenotypeLength(genotype.size());
}
public abstract Phenotype<Gene> getPhenotype();
public abstract void mutate();
//...
}
此类旨在扩展,子类显然提供了 getPhenotype() 和 mutate() 的实现。但是,我还有第二个类,它采用两个 Genotype 对象作为参数并返回一个包含 Genotype 对象的 ArrayList。由于此时我不知道扩展 Genotype 对象的类型,因此我需要使用如下通用参数:
public class Reproducer {
//...
private <G extends Genotype> ArrayList<Genotype> crossover(G parent1, G parent2) {
ArrayList<Genotype> children = new ArrayList<Genotype>();
ArrayList<Gene> genotypeOne = ArrayListCloner.cloneArrayList(parent1.getGenotype());
ArrayList<Gene> genotypeTwo = ArrayListCloner.cloneArrayList(parent2.getGenotype());
//one point crossover
int p = gen.nextInt(genotypeOne.size());
for (int i = 0; i < p; i++) {
genotypeOne.set(i, genotypeOne.get(i));
genotypeTwo.set(i, genotypeTwo.get(i));
}
for (int i = p; i < 10; i++) {
genotypeOne.set(i, genotypeTwo.get(i));
genotypeTwo.set(i, genotypeOne.get(i));
}
children.add(new G(genotypeOne)); //THROWS ERROR: Cannot instantiate the type G
children.add(new G(genotypeTwo)); //THROWS ERROR: Cannot instantiate the type G
return children;
}
}
但是,由于我需要在 ArrayList 中返回两个 G 类型的对象,我显然遇到了一个问题,我无法实例化新的 Genotype 对象,因为它们是 1. 泛型类型,并且可能是 2. 抽象类型。
这可能不是一起处理所有事情的糟糕方法,但如果有人有解决方案那就太好了。谢谢。
最佳答案
我建议在您的Genotype
类中使用工厂方法
public abstract class Genotype {
public abstract GenoType newInstance();
}
关于java - 实例化抽象类的通用扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7662408/