2015-11-24 26 views
0

我有一個zipcode,城市和州的文件。我需要創建一個類來存儲這些項目。這些對象將存儲在二叉搜索樹中,因此我只需要每個城市的一個條目,州組合。由於一些城市有多個郵政編碼,我被要求將郵政編碼存儲在班級的列表中。創建項目並將其添加到存儲在對象中的鏈接列表

基本結構:

public class Places(String city, String state, String zip){ 
    . . . 
} 

我相信我需要創建類中的LinkedList然後添加壓縮過它,但是當我這樣做,我得到一個空指針異常。

//create new LinkedList in Place 
     LinkedList<String> zips = new LinkedList<String>(); 
     zips.add(zip); 

我發現很多關於向列表添加對象但不在對象內使用列表的信息。

+0

需要更多的代碼!我看不到上面的代碼如何導致'NullPointerException'。這可能有所幫助:http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it – markspace

+3

你顯示的代碼片段應該不會引起'NullPointerException'。你一定在做別的事情。 –

+0

難道是'zip'爲null?你能發佈堆棧跟蹤嗎? – dave

回答

0

這應該工作:

public class LocationData{ 
    //Somewhere in your code initiate it, maybe in constructor? 
    public LinkedList<String> zips=new LinkedList<String>(); 
    //do the rest of what this class needs to do 
    } 

在使用LocationData另一個類:

public class TestClass { 
     //or any other method for that matter 
     public static void main(String[] args) { 
     LocationData ld=new LocationData(); 
     ld.zips.add("12345"); //adds zipcode of "12345" 
     } 
    } 

一個NullPointerException可以提出的唯一方法是,如果ldzips未初始化。由於您沒有發佈完整的代碼段,因此我無法確切知道您的異常情況。

+0

謝謝大家的意見。所以,文件中有一個空值的鏈接,所以鏈表引發了一個空指針異常。我將其更改爲數組列表,並且它工作正常。 謝謝, 仁 –

相關問題