1

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?

3
  • Show us the complete stack trace of the exception, the code of the the three classes, and the code that creates the array. Commented Jan 18, 2016 at 17:09
  • 3
    Likely instance Individual[] array was initialized as new SomeImplementingClass[], hence storing instances of the other implementing class would throw the ArrayStoreException. Hard to tell with the currently displayed code. Commented Jan 18, 2016 at 17:11
  • Yes you are right see my other comments I was indeed initialising it as SomeImplementingClass instead of interface. My bad Commented Jan 18, 2016 at 17:29

2 Answers 2

2

From the ArrayStoreException documentation:

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

My guess is that you initialize the individuals somewhere like this:

individuals = new BinaryIndividual[someLength];

Try to initialize it this way: individuals = new Individual[someLength];

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes my bad so stupid mistake, I was refractoring the code that was initially using only BinaryIndividuals and now I want to use different type individuals as well. Thanks my bad
2

Initialize your array first with some length:

Individual[] individuals = new Individual[sizeOfPopulation];

1 Comment

Yes you are correct I was initialising it into specific BinaryIndividuals instead of just Individuals. Thank you for your help guys I haven't spotted my mistake and I was sure there was something else wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.