PDA

View Full Version : java - arrays of my class - nullpointerexception




toddburch
Apr 15, 2007, 08:04 PM
This, seemingly simple construct, has me baffled. I've searched forums, the net, and my books, and I can't figure out it, although I am certain this is a very basic error.

I've defined my own class (MyTable) that is a simple data structure. I declare an array of them, but when I go to initialize them, I get a nullpointerexception right off the bat.

What is my idiotic error?


public class TestClassArray {
public static void main(String[] arg) {
int periods = 5 ;
MyTable[] tab = new MyTable[periods] ;
for ( int i = 0 ; i < periods ; i++ ) {
tab[i].age = 22 ;
tab[i].month = "Jan" ;
tab[i].balance = 100.99 ;
}
}
}

class MyTable {
int age ;
String month ;
double balance ;
}



toddburch
Apr 15, 2007, 08:07 PM
#$%$@&. Figured it out. I had only declared the variables, but never initialized (allocated storage for) anything.

I added tab[i] = new MyTable() ; as the first statement within my for loop and it fixed it right up.

Duh.

Thanks, Todd

(I'm right, right?)

stadidas
Apr 15, 2007, 08:45 PM
That's right. Before you just had an empty array and were trying to change values that didn't exist. You are now initialising a new object, inserting it, and then altering it's values directly.
However, it's good programming practise to write accessor and mutator methods to read and alter the values in a class, rather than accessing it's values directly. You'd do this by, for example, adding methods to the MyTable class like this:

public int getAge()
{
return age;
}

public void setAge(int i)
{
age = i;
}


and then in your loop changing:

tab[i].age = 22 ;


to:

tab[i].setAge(22);


Hope that helps :) .