Java中的哈希表覆盖问题

Dc *_*ing 0 java hashtable arraylist 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);  }
Run Code Online (Sandbox Code Playgroud)

我想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]}
Run Code Online (Sandbox Code Playgroud)

这很好

但是,当我用第二个字符串键插入第二个arraylist时,"bye"我得到了

在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,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]}

它覆盖了第一个arraylist.我每次都使用字符串数组来更改密钥,因此不应该发生.

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

有谁知道原因?

Roh*_*ain 6

不要finalTmList.clear()在你的for循环中做.这将清除指向的列表finalTmList,并随后清除指向该列表的所有引用.

因为,当您向其添加列表时Map,您不会添加指向您的副本List,而不是您的副本.因此,您对该引用或指向列表的任何引用所做的任何更改都将反映在所有引用中.copyList ReferenceListlist

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

finalTMlist = new ArrayList<Double>();
Run Code Online (Sandbox Code Playgroud)

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

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

并且也遵循同样的事情actualTFvalueforEachDoc.clear(),无论它是什么,因为我在代码中看不到声明.