Java中的哈希表覆盖问题

时间:2012-11-09 18:40:34

标签: java arraylist hashtable overwrite

我正在学习java,我无法使用put将数据添加到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);  }

我想使用ArrayList<Double>密钥将String放入哈希表中。

第一次通过循环我得到了密钥"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"插入第二个arraylist时,我得到了

  

在BM25TFIDF之后的最后一步之前{orange = [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,4.038037326690413,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。我每次都使用字符串数组来改变密钥,所以它不会发生。

我不确定它继续写作的原因。

有谁知道原因?

3 个答案:

答案 0 :(得分:6)

请勿在for循环中执行finalTmList.clear()。这将清除finalTmList指向的列表,并随后清除指向该列表的所有引用。

因为,当您向Map添加列表时,您不会添加List的副本,而是copy List Reference的副本相同的List。因此,您使用该引用或指向列表的任何引用对list所做的任何更改都将反映在所有引用中。

您应该在for循环中为地图的每个条目创建一个新列表: -

finalTMlist = new ArrayList<Double>();

将上述语句移到第一个for循环中。

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

对于actualTFvalueforEachDoc.clear()也是如此,无论它是什么,因为我在代码中看不到声明。

答案 1 :(得分:1)

您应该为地图中的每个条目创建一个新的ArrayList

答案 2 :(得分:1)

您必须在开始新的迭代之前创建一个新的数组列表

actualTFvalueforEachDoc = new ArraList<Double>();