javaooparraylist

Using ArrayLists as static properties in classes?


struggling a bit with something. I have built a proof of concept and googled but can't find reason.

  1. I am currently trying to use an ArrayList as a static property in a class to store series of entries. The only problem is that everytime I try add to the Totalentries arraylist I get a nullPointerError.

Would appreciate some guidance as to where I am going wrong?

My Class:

import java.util.ArrayList;


public class Competition {
private static ArrayList totalentries;

public Competition(){


}
public void newEntry(){
    totalentries.add("an Entry");
}

}

My Test Code:

public class testEntries {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Competition myComp=new Competition();
        myComp.newEntry(); //Null Pointer comes here!
        myComp.newEntry();
        myComp.newEntry();
        myComp.newEntry();
        myComp.newEntry();
        myComp.newEntry();

        myComp.toString();
    }

}

Solution

  • You never instantiated totalentries in your Competition class.

    You would need something like:

    private static ArrayList totalentries = new ArrayList();
    

    However, note that I would advise against keeping this "static". Otherwise, every "Competition" you create will be sharing the same list of entries, which is likely not what you really want.

    Also, declare your types using interfaces, than instantiate with types. You may also want to use Generics here. So even better (and following standard naming conventions):

    private List<String> totalEntries = new ArrayList<String>();