【发布时间】:2011-10-05 13:54:19
【问题描述】:
尝试为遗传算法编写一些通用代码,我有一个抽象类 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. 抽象的。
这可能是一种不好的方式来处理所有事情,但如果有人有一个很棒的解决方案。谢谢。
【问题讨论】:
标签: java generics parameters abstract instantiation