gpt4 book ai didi

存储类实现接口(interface)时出现 Java ArrayStoreException

转载 作者:行者123 更新时间:2023-12-01 21:53:03 27 4
gpt4 key购买 nike

您好,当我尝试将实现接口(interface)的类存储到定义为接口(interface)数组的数组中时,我收到此 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;
}
}

Individual 是 BinaryIndi​​vidual 和 StringIndividual 类都实现的接口(interface)。问题出在哪里?

最佳答案

来自 ArrayStoreException 文档:

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

我的猜测是你在像这样的地方初始化个体:

individuals = new BinaryIndividual[someLength];

尝试以这种方式初始化它:individuals = new individual[someLength];

关于存储类实现接口(interface)时出现 Java ArrayStoreException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34860275/

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