java - arrays of my class - nullpointerexception

Discussion in 'Mac Programming' started by toddburch, Apr 15, 2007.

  1. toddburch macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #1
    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 ; 
    }
     
  2. toddburch thread starter macrumors 6502a

    Joined:
    Dec 4, 2006
    Location:
    Katy, Texas
    #2
    #$%$@&. 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?)
     
  3. stadidas macrumors regular

    Joined:
    Feb 27, 2006
    Location:
    Kent, United Kingdom
    #3
    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 :) .
     

Share This Page