Hi I'm getting this Java ArrayStoreException when I try to store class that implements interface into array that's defined as array of interfaces. Here's the code:
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 is interface that both classes BinaryIndividual and StringIndividual implement. Where is the problem?
Individual[]array was initialized asnew SomeImplementingClass[], hence storing instances of the other implementing class would throw theArrayStoreException. Hard to tell with the currently displayed code.