1

I have a method in a client server program which is meant to create an instance of a citylist class, which is just an array list of cities...

(This method is in server)

public void listCities() {
    CityList LoadCities = new CityList();
    String CityDetails = LoadCities.cities.toString();
    try {
        dos.writeUTF("These are the cities serviced by the ssystem");
        dos.writeUTF(ServerConstants.CR_LF);
        dos.writeUTF(CityDetails);
    } catch (IOException ex) {
        Logger.getLogger(SocketHandler.class.getName()).log(Level.SEVERE, null, ex);
    }

}

The CityList Class is this:

public class CityList {

public ArrayList<City> cities;
    City melbourne = new City("Melbourne");
    City sydney = new City("Sydney");
    City darwin = new City("Darwin");
    City launceston = new City("Launceston");
    City hobart = new City("Hobart");

//default constructor
public CityList() {
    cities.add(melbourne);
    cities.add(sydney);
    cities.add(darwin);
    cities.add(launceston);
    cities.add(hobart);
}


//other constructor
public CityList(ArrayList<City> cities) {
    this.cities = cities;
}

public int size()
{
    return cities.size();
}



}

The client exists in a thread... The server calls a socket handler in its own thread class SocketHandler extends Thread class SocketHandler extends Thread

I continually get this error when I try to call that particular method (list cities)

Exception in thread "Thread-0" java.lang.NullPointerException
at hotelbroker.CityList.<init>(CityList.java:30)
at hotelbroker.SocketHandler.listCities(MultiEchoServer.java:153)
at hotelbroker.SocketHandler.run(MultiEchoServer.java:95)

I know this is cuz I'm a n00b and I need to call some kind of this instance thingummy I just have no idea...

1
  • 4
    public ArrayList<City> cities; is not initialized. Commented Apr 14, 2014 at 2:28

2 Answers 2

1

When you don't initialize instance fields, they get initialized to null by default. In this case, you are trying to use this instance variable

public ArrayList<City> cities;

without having first intialized it. It's therefore null.

When you try to invoke a method on a null reference, like here

cities.add(melbourne);

you get a NullPointerException.

You have to initialize it, either where it is declared

public ArrayList<City> cities = new ArrayList<>();

or before you use it

cities = new ArrayList<>();
cities.add(melbourne);
Sign up to request clarification or add additional context in comments.

Comments

0
public CityList() {
    cities = new ArrayList<City>();
    cities.add(melbourne);
    cities.add(sydney);
    cities.add(darwin);
    cities.add(launceston);
    cities.add(hobart);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.