Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

toddburch

macrumors 6502a
Original poster
Dec 4, 2006
748
0
Katy, Texas
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?

Code:
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 ; 
}
 
#$%$@&. Figured it out. I had only declared the variables, but never initialized (allocated storage for) anything.

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

Duh.

Thanks, Todd

(I'm right, right?)
 
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:
Code:
public int getAge()
{
    return age;
}

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

and then in your loop changing:
Code:
tab[i].age = 22 ;

to:
Code:
tab[i].setAge(22);

Hope that helps :) .
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.