Sign in to follow this  
slackey

NullPointerException in java

Recommended Posts

For Comp Sci class I am creating a prison simulation since we are learning about searches and sorts. I have 3 classes in this project, a Prisoner class, a Prison class, and a driver class with a main method to run the prison. The Prisoner class defines a prisoner, and the Prison class is essentially an ArrayList of prisoners with methods to add, remove, sort, and search through the prisoners. My problem is I keep getting a NullPointerException when I try to add a Prisoner object to the ArrayList in the Prison class. In my Prison class I have the following method:
public boolean addPrisoner(Prisoner p)
{
	if(population < capacity)  //checks to make sure there is room in the prison
	{
		prisoners.add(p);  //prisoners is the ArrayList containing all prisoners
		population++;      //population is increased when prisoner is added
		return true;
	}
	else
		return false;
}
In the driver program I create a new Prison object, then create a Prisoner object. When I call the addPrisoner method to add the Prisoner to the Prison, I get a NullPointerException and I am not sure why. I'd like to figure out why I am getting this exception so that then I can fix it.

Share this post


Link to post
Share on other sites
Try adding some logging statements (System.Out.Println()) to check that prisoners isn't null. Either it or p is null. You have actually allocated prisoners with new, haven't you?

And does ArrayList not have a size() or count() member (It's been ages since I used Java)? That'd mean you can get rid of population.

Share this post


Link to post
Share on other sites
How hard is this?


public class Prison
{
private ArrayList prisoners = new ArrayList();
private int capacity = 0;

public Prison(int c)
{
capacity = c;
}

public boolean addPrisoner(Prisoner p)
{
if(prisoners.size() < capacity) //checks to make sure there is room in the prison
{
prisoners.add(p); //prisoners is the ArrayList containing all prisoners
return true;
}
else
return false;
}
}



Toolmaker

Share this post


Link to post
Share on other sites
In Java, variables of object type are effectively pointers, and they get default-initialized to null whenever they actually are default-initialized. Therefore if you declare a class member ArrayList like this:


private ArrayList prisoners;


Then it is equivalent to


private ArrayList prisoners = null;


and not to Toolmaker's version.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this