4

This may sound silly, but, I get this error while casting from List to Array:

ArrayStoreException: null

The code that i am using right now is :

public void onSuccess(List<Agent> resultList) {

    Agent[] array = new Agent[resultList.size()];
    resultList.toArray(array);

Agent its a class that i have defined with their own field definitions, being all of them private final Strings

But i dont know what i could be missing atm.

Thank you in advance for your help.

Kind regards,

6
  • 1
    So like, you actually didn't get a useful stacktrace when it threw the exception? Commented Nov 27, 2013 at 23:32
  • This should work. Are you sure resultList isn't null? Commented Nov 27, 2013 at 23:35
  • I think he would get NullPointerException if it was, right? Commented Nov 27, 2013 at 23:37
  • 2
    @peter.petrov: yes, correct. The docs specify ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of every element in this list. It's just guessing until he shows some code, though. Commented Nov 27, 2013 at 23:39
  • I see. I thought he has null in the list but seems it's not that too. Commented Nov 27, 2013 at 23:39

1 Answer 1

4

You're probably passing your ArrayList<Agent> to some method which has just an ArrayList or List parameter (untyped). This method can pass compilation but mess things up at runtime. Example below.

If you comment out the call to messUp in my example things are OK. But messUp can add things which are not Agents to your list, and cause problems this way.

This is my best guess without seeing your code.

Hope it helps.

import java.util.ArrayList;
import java.util.List;


public class Test009 {

    public static void main(String[] args) {
        List<Agent> resultList = new ArrayList<Agent>();
        resultList.add(null);
        resultList.add(new Agent1());
        resultList.add(new Agent());
        messUp(resultList);
        test(resultList);
    }

    private static void messUp(List lst){
        lst.add("123");
    }

    public static void test(List<Agent> resultList){
        Agent[] array = new Agent[resultList.size()];
        resultList.toArray(array);
        System.out.println("done");     
    }
}

class Agent {
    protected int x;
}

class Agent1 extends Agent{
    protected int y;
}

Additional Note: OK, well, this doesn't explain the "null" part of your error message. So the root cause is somewhat different.

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

Comments

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.