2012-12-27 23 views
0

反對我創建包含幾何要素和屬性對象:NullPointExeption時儘量把變量在Java中

public class Feature { 
Feature(String wkt) { 
this.wkt = wkt; 
} 

private HashMap<Column, String> columnMap; 
private String wkt; 

public String getWKT() { 
return wkt; 
} 
public void addAttribute(Column column, String value) { 
columnMap.put(column, value); 
} 
public String getAttribute(String column) { 
return columnMap.get(column) ; 
} 
public Map<Column, String> getAttributes(){ 
    return columnMap; 

} 
} 

WKT是幾何體。 ColumnMap是對象包含的屬性的HashMap:

public class Column { 

private String columnName; 

Column(String columnName) { 
    this.columnName = columnName; 
} 

public String getName() { 
    return columnName; 
} 
} 

現在我說:

columnList = new ArrayList<Column>(columns); 

...... 

Feature feature= new Feature(WKT); 
for(int p=0;p<columnList.size();p++){ 
for(int k=0;k<=ViewObject.getMIDInfo(totalObjects).length;k++){ 
    if(p==k){ 
     System.out.println("Column "+columnList.get(p).getName()+" Value "+ ViewObject.getMIDInfo(totalObjects)[k].toString()); 
     //feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString()); 
    } 
} 
} 

並獲得輸出:

Column id Value 22 
Column kadnumm Value "66-41-0707001-19" 

所以,我怎麼理解columnListViewObject.getMIDInfo(totalObjects)是不是空的。在此之後我改變:

//feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString()); 

到:

feature.addAttribute(columnList.get(p), ViewObject.getMIDInfo(totalObjects)[k].toString()); 

並獲得exeption:

Column id Value 22 
java.lang.NullPointerException 
at objects.Feature.addAttribute(Feature.java:18) 
at objects.MIFParser.findRegion(MIFParser.java:181) 
at objects.MIFParser.instanceNextObject(MIFParser.java:66) 
at Read.main(Read.java:40) 

NullPointerException異常如何我明白意味着我嘗試使用空的對象?怎麼了?
P.s.對不起,我的英語可能會很糟糕,特別是標題。在要素類的構造函數this.columnMap = new HashMap<Column, String>();

UPDATE

奧基我添加此。

但現在我試着做:

System.out.println(feature.getAttribute("id")+" "+feature.getAttribute("kadnumm")); 

輸出:

null null 

什麼可能是錯誤的?

+0

我投票給所有其他答案,CID他們都是一樣的。只是把它放在那裏。 – Bohemian

回答

2

addAttribute試圖把東西放在columnMap上,但是你不會在任何地方創建columnMap。您需要添加到您的Feature構造:

Feature(String wkt) { 
    this.wkt = wkt; 
    this.columnMap = new HashMap<Column, String>(); // <=== The new bit 
} 

...或添加初始化到你的宣言:

private HashMap<Column, String> columnMap = new HashMap<Column, String>(); 
//      The new bit--- ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

剛剛宣佈成員是不夠的,成員只是指對象,並從null開始。您需要創建該對象來引用它並將該對象分配給它。

+0

'this.columnMap = new HashMap ();'這個幫助。但我得到了另一個問題。請看我的問題更新。 –

3

你沒有初始化columnMap:當您創建功能的新實例

private HashMap<Column, String> columnMap = new HashMap<Column, String>(); 
2

columnMap對象未初始化。因此,它是空當你在addAttribute

2

調用columnMap.put(column, value);而不是

​​3210

private HashMap<Column, String> columnMap = new HashMap<Column, String>(); 
1

您必須初始化地圖:

private HashMap<Column, String> columnMap = new HashMap<Column, String>();