2014-04-14 107 views
1

我有一個客戶端服務器程序中的方法,這意味着創建一個citylist類的實例,它只是一個城市的數組列表...線程「Thread-0」中的異常java.lang.NullPointerException

(此方法是在服務器)

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調用一個套接字句柄EXT結束線程 類的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,我需要調用我不斷地得到這個錯誤某種這種實例thingummy我只是不知道...

+4

'公共的ArrayList 城市;'未初始化。 –

回答

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

..........謝謝! –

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