嗨,当我尝试将实现接口的类存储到定义为接口数组的数组中时,出现了Java ArrayStoreException。
这是代码:

private Individual[] individuals;
/*
* other fields and methods here
*/

//This method runs alright
public void initializePopulationBinary() {
    for(int i = 0; i < sizeOfPopulation; i++) {
        BinaryIndividual individual = new BinaryIndividual();
        individual.generateRandomIndividual();
        this.individuals[i] = individual;
    }
}
//This methods throws exception
public void initializePopulationString() {
    for(int i = 0; i < sizeOfPopulation; i++) {
        StringIndividual individual = new StringIndividual();
        individual.generateRandomIndividual();
        this.individuals[i] = individual;
    }
}


个体是两个类BinaryIndi​​vidual和StringIndividual实现的接口。哪里有问题?

最佳答案

ArrayStoreException文档:


  表示已尝试将错误类型的对象存储到对象数组中。


我的猜测是您可以像这样在individuals初始化某处:

individuals = new BinaryIndividual[someLength];


尝试通过以下方式初始化它:individuals = new Individual[someLength];

10-07 14:12