2012-11-09 85 views
0

我正在學習java,我無法使用put將數據添加到Java哈希表中。java中的哈希表覆蓋問題

我有這樣的代碼

double finalIDF = 0.0; 
double finalIDF = 0.0; 
double finalBM = 0.0; 

ArrayList<Double> finalTMlist = new ArrayList<Double>(); 
Hashtable<String, ArrayList<Double>> BM25TFIDF = new Hashtable<String, ArrayList<Double>>(); 
String[] bm25QueryList // this is the array to store strings like {hey , good , by} 

for(int finalindex = 0; finalindex < bm25QueryList.length ; finalindex++) 
{ 
actualTFvalueforEachDoc.clear(); 
finalTMlist.clear(); 
finalIDF = 0.0; 
finalIDF = htBM25IDF.get(bm25QueryList[finalindex]); 
finalTMlist = tfForAlldoc.get(bm25QueryList[finalindex]); 


for(int innerfinal = 0 ; innerfinal < finalTMlist.size() ; innerfinal++){ 
finalTM =finalTMlist.get(innerfinal); 
finalBM = finalIDF * finalTM; 
actualTFvalueforEachDoc.add(finalBM); 
finalTM = 0.0; 
finalBM = 0.0; } 
BM25TFIDF.put(bm25QueryList[finalindex], actualTFvalueforEachDoc); 
System.out.println("Right before final step after BM25TFIDF " + BM25TFIDF); } 

我想用String鍵將ArrayList<Double>到哈希表。

第一次通過循環我拿到了鑰匙"orange"

Right before final step after BM25TFIDF {orange=[1.1698113207547172, 1.0508474576271187, 0.8682367918523235, 1.6330439988027539, 0.8938401048492793, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0133729569093612, 0.0]} 

這是很好的

然而,當我插入與第二串鍵"bye"我得到

第二數組列表

就在BM25TFIDF {orange = [0.0,0.0,0.0, 0.0,0.0,0.0,0.0,0.0,4.238037326690413,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0],bye = [0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0] 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0]}

它覆蓋第一個數組列表。我使用字符串數組每次更改密鑰,所以不應該發生。

我不確定寫作的原因。

有沒有人知道原因?

+0

你把同一列表到表兩次,因爲你永遠只能做'新的ArrayList <...>()'一次。 –

回答

6

不要在你的for循環中做finalTmList.clear()。這將清除finalTmList指向的列表,並隨後清除指向該列表的所有參考。

因爲,當您添加列表中Map,您不添加您的List的副本,而你的List Referencecopy,即指向相同的List。因此,您對該引用所做的任何更改list或指向該列表的任何引用都將反映在所有引用中。

finalTMlist = new ArrayList<Double>(); 

將上述語句中的第一個for循環 - :

你還是在你的for循環,爲地圖的每個條目創建一個新的列表。

for(int finalindex = 0; finalindex < bm25QueryList.length ; finalindex++) { 
    finalTMlist = new ArrayList<Double>(); 
    // Your rest code. 

,並按照actualTFvalueforEachDoc.clear()也同樣的事情,不管它是什麼,因爲我看不到代碼的聲明。

+0

感謝它的工作原理我改變actualTFvalueforEachDoc和finalTMlist到新的ArrayList ();.那麼它就會罰款。我想這是所有局部變量(我認爲可以清除)。如果你沒事就能解釋一下參考嗎? –

+0

@DcRedwing ..編輯第一段。你可以看到。 –

+0

@DcRedwing ..增加了一些內容。 –

1

您應該爲地圖中的每個條目製作一個新的ArrayList

+0

謝謝!有用!!!那麼,「.clear()」和「new ArrayList」之間有什麼區別? –

+0

@DcRedwing這是一個關於面向對象方法的長篇討論,簡而言之,對象變量是引用而不是值,所以把相同的列表放在地圖中,即使它們在不同的條目中,也會指向相同的列表,所以'.clear )'將清除所有**條目中的列表,而新列表將允許將一個列表區分爲另一個列表。 – Mordechai

1

你之前創建一個新的數組列表開始一個新的迭代

actualTFvalueforEachDoc = new ArraList<Double>();