ArrayList and recieving nullPointerExceptions.

M

Mitch

Hi.

I am having trouble with a set of ArrayLists which when I use the
ArrayListReference.add(object); method i recieve a null pointer error.
This puzzled me because A) I thought that the point of Arraylist was
that you didn't have to worry with null pointers etc as you can simply
add items and get items and let the ArrayList object deal with the
details. B) Is the fact that I have used them ahppily already in my
program design.

I can supply code if you like but the details are

Class A
{

...


Station.addPassenger(P);

}

Class Station
{

...

public void addPassenger(Passenger P)
{

stationPassengerList.add(P)
}

}


This set up is recieving nullPointerExceptions at runtime.

Now I have done some reading around both on this group and elsewhere
and there is a major possibility I can see. I see that trying to add a
null value to the ArrayList will result in a nullPointerException In my
constructor for passenger i have a line that println's "Passenger made"
and this prints fine, however if i was to then call the method below
immeadiately after calling the constructor I get a compilation error
saying symbol cant be found

Passenger P = new Passenger(startStationReference,
stopStationReference);
System.out.Println("New passenger starts
at test " + P.getStartStation().getNameOfStation() );

startStationReference.addPassengerToStation(P);

commenting out the println lets the program compile and then gives me
the nullpointerexception at runtime.

So my querstion is along the lines of if Passenger P = new Passenger();
only creates a reference to a new passenger object (This is what i read
elsewhere and had never heard before) then how does it become an object
and what must i do to change it so that it can be referenced. I have
never had any troubles like this before.

Kind Regards, and hope i have been clear enough.

Mitch.
 
I

Ike

you need to actually create the ArrayList. It is the ArrayList which is null
here, like this:

import java.util.ArrayList;

Class Station
{
ArrayList stationPassengerList = new ArrayList();
....

//Ike
 
M

Mitch

Passenger P = new Passenger(startStationReference,
stopStationReference);
//this constructer has a println

//method that prints

//Line that says symbol not found (I have approprite imports)
system.out.println("New Passenger starts at " +
P.getStartStation().getNameOfStation() );

//Method called that causes trouble at runtime if above line not
present
startStationReference.addPassengerToStation(P);

///////////////////////////

//In the Station class to which startStationReference is an object of

public void addPassengerToStation(Passenger P)
{
stationPassengerList.add(P);
}



//and in the constructor for Station

ArrayList<Passenger> stationPassengerList = new ArrayList<Passenger>();
stationPassengerList.ensureCapacity(400);



//Hope this clarifies a bit
 
M

Mitch

Thank you Ike but as you can see in the last section of my previous
post i am creating the ArrayList.

Also apologies, i spent ten minutes formating my code then hit post and
it screwed it up. It was supposed to be properly formatted.
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
NotDashEscaped: You need GnuPG to verify this message

Mitch schreef:
Passenger P = new Passenger(startStationReference,
stopStationReference);
//this constructer has a println

//method that prints

//Line that says symbol not found (I have approprite imports)
system.out.println("New Passenger starts at " +
P.getStartStation().getNameOfStation() );

//Method called that causes trouble at runtime if above line not
present
startStationReference.addPassengerToStation(P);

///////////////////////////

//In the Station class to which startStationReference is an object of

public void addPassengerToStation(Passenger P)
{
stationPassengerList.add(P);
}



//and in the constructor for Station

ArrayList<Passenger> stationPassengerList = new ArrayList<Passenger>();
stationPassengerList.ensureCapacity(400);



//Hope this clarifies a bit

It doesn´t We cannot help you if you do not provide enough code. What
is getStartStation(), getNameOfStation() etc. Please provide working code.

H.

--
Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFEEDJ0e+7xMGD3itQRAkl3AJ40q9RNPm1eRlZVwL6/RfGhEPeQRgCeN5cp
DQjKZpufYfegfX7ezxPb9KU=
=SDm/
-----END PGP SIGNATURE-----
 
M

Mitch

Ok

adding the lines

if(P == null){System.out.println("P is null");}
if(P != null){System.out.println("P is not null");}

prints out P is not null. so P is not null but calling a method from P
IE

System.out.Println("New passenger starts at test " +
P.getStartStation().getNameOfStation() );

errors saying symbol not found.



Also I have established that my working ArrayList has the form

#Initiate List

#in same code block add elements

However my non working arraylists are of the form

#initiate array list in constructor

#try to access afterwards from external objects (using mutator methods)

Is this where the problem lies? Can they not be instantiated from the
objects constructor (each object needs its own arraylist) If so is
there a way around this problem?

Currently my constructor looks like this:

public Station(String nameOfStation)
{
this.nameOfStation = nameOfStation;
ArrayList<Passenger> stationPassengerList = new
ArrayList<Passenger>();
stationPassengerList.ensureCapacity(400);
}
 
M

Mitch

Ok the code that initiates the Passengers (This is for a simulated Rail
network in case you were wondering) goes like this:

Code:
Random generator = new Random();


//For Red to LTV
for( int i = 0; i < 1000; i++)
{
hasPassengerBeenSetup = false;
//Get start station
while(hasPassengerBeenSetup == false)
{
randomIndex =
generator.nextInt(REDDITCHtoLICHFIELD_TRENT_VALLEY.size() - 10);

//so that station 1
//is before station 2
do
{


randomIndex2 =
generator.nextInt(REDDITCHtoLICHFIELD_TRENT_VALLEY.size());
} while(randomIndex2<=randomIndex);

if( REDDITCHtoLICHFIELD_TRENT_VALLEY.get(randomIndex)
instanceof Station & REDDITCHtoLICHFIELD_TRENT_VALLEY.get(randomIndex2)
instanceof Station) //These indexs can be either
//Stations or Signals or Points
{
startStationReference =
(Station)REDDITCHtoLICHFIELD_TRENT_VALLEY.get(randomIndex);
stopStationReference =
(Station)REDDITCHtoLICHFIELD_TRENT_VALLEY.get(randomIndex2);
passengerCount++;
System.out.println("Passenger number " +
passengerCount + " will start at " +
startStationReference.getNameOfStation());
System.out.println("Passenger number " +
passengerCount + " will stop at " +
stopStationReference.getNameOfStation());

Passenger P = new Passenger(startStationReference,
stopStationReference);
//This line casue trouble
//                             System.out.Println("New passenger starts
//at test " + P.getStartStation().getNameOfStation() );
if(P == null){System.out.println("P is null");}
if(P != null){System.out.println("P is not null");}

//this line also casues trouble
//                   startStationReference.addPassengerToStation(P);
hasPassengerBeenSetup = true;

}
}//end while
}//end for

And my passenger class is



Code:
/*
* Passenger.java
*
* Created on 25 February 2006, 15:21
*
* Created By Mitchell Kent
*/

package fyp_rail_simulation;

/**
* Passengers travel on the train on my simulated rail network,
* I chose to use a class for Passenger so that Driver and Staff
* could be inherited from it.
* @author Mitch
*/
public class Passenger {

/**
* Creates a new instance of Passenger
*
* Passengers travel on the train on my simulated rail network,
* I chose to use a class for Passenger so that Driver and Staff
* could be inherited from it. This constructor initiates with a
* start station and a stop station, where the passenger will board
* and alight.
* @param startStation Station where pasenger will board
* @param endStation Station where passenger will alight
*/
public Passenger(Station startStation,
Station endStation) {
this.startStation = startStation;
this.endStation = endStation;
System.out.println("Passenger made ok");
}

/**
* Accessor method. Returns Station of Boarding
* @return Returns station of boarding
*/
public Station getStartStation()
{
return this.startStation;
}
/**
* Accessor Method.  Returns Station to alight on
* @return Returns station to alight on
*/
public Station getEndStation()
{
return this.endStation;
}

/**
* Station to board on
*/
private Station startStation;
/**
* Station to alight on
*/
private Station endStation;
/**
* Boolean to say if poassenger is travelling, not yet implemented.
*/
private boolean enRoute = true;
}



I think the problem lies in that i am trying to instantiate the
ArrayList from within the Passenger Constructor method.
 
M

Mitch

Oh the above is wrong, i am trying to instantiate the ArrayList for the
Station Constructor, for which the class is below

Code:
/*
* Station.java
*
* Created on 24 February 2006, 23:43
*
* Created By Mitchell Kent
*/

package fyp_rail_simulation;
import java.util.*;

/**
* This is a station object that the train will interact with (exchange
passengers etc)
* @author Mitch
*/
public class Station extends RailSection{

/**
* Creates a new instance of Station
* @param nameOfStation A String description of the name of the
station
*/
public Station(String nameOfStation) {
this.nameOfStation = nameOfStation;
ArrayList<Passenger> stationPassengerList = new
ArrayList<Passenger>();
stationPassengerList.ensureCapacity(400);

}

/**
* Accessor method to get name of String
* @return String representation of the name of the station
*/
public String getNameOfStation()
{
return nameOfStation;
}

/**
* This checks for any passengers wishing to board the train that
calls it and returns them as a list
* @return ArrayList of Pasenger objects that should 'board the
train
*/
public ArrayList<Passenger> checkForNewPassengers()
{
return stationPassengerList;
}

/**
* Removes all Pasengers from Station
*/
public void clearStationOfPassengers()
{
stationPassengerList.clear();
}

/**
* Adds a Passenger object to the station
* @param P Passenger object to be added to the train
*/
public void addPassengerToStation(Passenger P)
{
stationPassengerList.add(P);
}

/**
* Text representation of the name of the station
*/
private String nameOfStation;
/**
* Iterator
*/
private int i;
//  private ArrayList<Passenger> stationPassengerList;
/**
* Passenger
*/
private Passenger P;


}

This class is interesting and the reason I think my problem lies with
the constructor method is becasue all my methods in the clas that rely
on the ArrayList<Passenger> are showing up red (underlined / erroring)
saying they can find the variable stationPassengerList which has ben
setup in the Constructor.
 
J

Jussi Piitulainen

Mitch said:
Is this where the problem lies? Can they not be instantiated from
the objects constructor (each object needs its own arraylist) If so
is there a way around this problem?

Currently my constructor looks like this:

public Station(String nameOfStation)
{
this.nameOfStation = nameOfStation;
ArrayList<Passenger> stationPassengerList = new
ArrayList<Passenger>();
stationPassengerList.ensureCapacity(400);
}

Do this:

ArrayList stationPassengerList;

public Station() {
stationPassengerList = new ArrayList();
}

If you declare a variable inside a constructor, it is local to the
constructor. You need to declare it outside and only assign inside.
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
NotDashEscaped: You need GnuPG to verify this message

Mitch schreef:
Oh the above is wrong, i am trying to instantiate the ArrayList for the
Station Constructor, for which the class is below

Code:
/*
* Station.java
*
* Created on 24 February 2006, 23:43
*
* Created By Mitchell Kent
*/

package fyp_rail_simulation;
import java.util.*;

/**
* This is a station object that the train will interact with (exchange
passengers etc)
* @author Mitch
*/
public class Station extends RailSection{

/**
* Creates a new instance of Station
* @param nameOfStation A String description of the name of the
station
*/
public Station(String nameOfStation) {
this.nameOfStation = nameOfStation;
ArrayList<Passenger> stationPassengerList = new
ArrayList<Passenger>();[/QUOTE]

This is a local arraylist now, it does no longer exist once the
constructor is finished.
[QUOTE]
stationPassengerList.ensureCapacity(400);

}[/QUOTE]
[QUOTE]
//  private ArrayList<Passenger> stationPassengerList;[/QUOTE]

^^^^^^^ why did you comment this out?  Of course it doesn?t work.

H.

--
Hendrik Maryns

==================
www.lieverleven.be
http://aouw.org
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2 (GNU/Linux)

iD8DBQFEED8Ne+7xMGD3itQRAlT+AKCDTIIAqquBwjaCiNwSJuRVCNfndwCfdlPU
FjRxVTFbiquVHcEJFkE5BsY=
=4S8n
-----END PGP SIGNATURE-----
 
T

Thomas Weidenfeller

Mitch said:
prints out P is not null. so P is not null but calling a method from P
IE

System.out.Println("New passenger starts at test " +
P.getStartStation().getNameOfStation() );

You are not only calling a method from P, but also a second one on the
result returned by that.

So, if

P.getStartStation()

returns a null, then

P.getStartStation().getNameOfStation()

of course will give you a NullPointerException. You might want to
consider using a debugger to step through the code and check what
happens where.

/Thomas
 
M

Mitch

Thank you all, though Jussi hit the nail on the head. I forgot that
declaring a variable inside the method kept it local. That is why all
methods relying on this ArrayList were also returning null pointer
exceptions.

And to Hendrik i was in the middle of trying to debug that section,
seeing what effects each line had etc, that is probably why that line
was commented out at that point. I was re-declaring it in the
constructor.

A classic example of the stuff they teach you in lectures but you learn
through experience.

Thank you all very much!

Mitch.
 
N

Nigel Wade

Mitch wrote:

//This line casue trouble
// System.out.Println("New passenger starts
//at test " + P.getStartStation().getNameOfStation() );
ArrayList from within the Passenger Constructor method.

Probably because PrintStream (System.out) does not contain the method Println().
 
M

Mitch

ha, yeah thanks, but i have noticed that since. Once I got all the
above working that line was still erroring and it drew my attention.
Cheers though. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top