Search code examples
javaarraysoopjdbcstruts

Array of Objects Null Pointer exception


I am creating an array of objects like this

            RMCUser[] rmc = new RMCUser[resultList.size()];
            int i = 0;

            for (Iterator iter = resultList.iterator(); iter.hasNext();) {
            Object[] objArr = (Object[]) iter.next();

        appl_id = objArr[0].toString();
        rmc[i].setAppl_id(appl_id);
                       i++}

I get a nullpointer exception in the rmc[i].setAppl_id line. My resultList size is 1.


Solution

  • You're never initializing the values in the array. When you create an array and don't explicitly initialize the values in it they default to an appropriate value based on the type. In your case, null.

    The fix is to explicitly initialize each value.

    RMCUser[] rmc = new RMCUser[resultList.size()];
    for (int i = 0; i < rmc.length(); i++)
    {
        rmc[i] = new RMCUser();
        ... // do whatever else you need to do with it here
    }