我在客户端服务器程序中有一个方法,用于创建citylist类的实例,它只是一个城市的数组列表......
(此方法在服务器中)
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);
}
}
CityList类是这样的:
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();
}
}
客户端存在于一个线程中......服务器在自己的线程类中调用一个套接字处理程序SocketHandler扩展了Thread class SocketHandler扩展Thread
当我尝试调用该特定方法(列出城市)时,我不断收到此错误
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)
我知道这是因为我是一个n00b,我需要打电话给某个实例,我只是不知道......
答案 0 :(得分:1)
如果不初始化实例字段,默认情况下它们会初始化为null
。在这种情况下,您尝试使用此实例变量
public ArrayList<City> cities;
没有首先初始化它。因此null
。null
。
当您尝试在cities.add(melbourne);
引用上调用方法时,就像这里
NullPointerException
你得到public ArrayList<City> cities = new ArrayList<>();
。
你必须在声明它的地方初始化它
cities = new ArrayList<>();
cities.add(melbourne);
或在您使用之前
{{1}}
答案 1 :(得分:0)
public CityList() {
cities = new ArrayList<City>();
cities.add(melbourne);
cities.add(sydney);
cities.add(darwin);
cities.add(launceston);
cities.add(hobart);
}