我正在学习 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
进入哈希表关键。
第一次通过循环我得到了 key "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"
插入第二个数组列表时我明白
Right before final step after 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]}
它正在覆盖第一个数组列表。我每次都使用字符串数组来更改 key ,所以它不应该发生。
我不太确定它不断写下去的原因。
有谁知道原因吗?
最佳答案
不要在 for 循环中执行 finalTmList.clear()
。这将清除 FinalTmList 指向的列表,随后清除指向该列表的所有引用。
因为,当您将列表添加到Map
时,您并不是添加List
的副本,而是添加List
的副本
List Reference
,指向同一个List
。因此,您使用该引用或任何指向该列表的引用对该列表
所做的任何更改都将反射(reflect)在所有引用中。
您应该在 for 循环中为 map 的每个条目创建一个新列表:-
finalTMlist = new ArrayList<Double>();
将上述语句移至第一个 for 循环内。
for(int finalindex = 0; finalindex < bm25QueryList.length ; finalindex++) {
finalTMlist = new ArrayList<Double>();
// Your rest code.
并且对 actualTFvalueforEachDoc.clear()
也遵循相同的操作,无论它是什么,因为我在代码中看不到声明。
关于java - java中的哈希表覆盖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13314004/