Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayStoreException: null while casting List to Array

Tags:

java

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,

like image 231
Catersa Avatar asked Nov 01 '25 12:11

Catersa


1 Answers

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.

like image 93
peter.petrov Avatar answered Nov 04 '25 03:11

peter.petrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!