I am studying java and I am having trouble using put to add data into a Java hashtable.
I have this code
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); }
I would like to put the ArrayList<Double> into the hashtable using a String key.
The first time through the loop I got the 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]}
which is fine
However, when I insert the second arraylist with second string key "bye" I get
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]}
It is overwriting the first arraylist. I used string array to change the key every time, so it shouldn’t be happen.
I am not really sure the reason that it keeps over writing.
does anyone know the reason ?
Don’t do
finalTmList.clear()in your for loop. That will clear the list pointed to by thefinalTmList, and subsequently for all the reference pointing to that list.Since, when you add a list to the
Map, you are not adding a copy of yourList, rather acopyof yourList Reference, that points to the sameList. So, any change you make to thatlistwith that reference, or any reference pointing to the list, will be reflected in all the reference.You should rather create a new list in your for loop, for each entry of your Map: –
Move the above statement inside your first for loop.
And follow the same thing for
actualTFvalueforEachDoc.clear()also, whatever it is, as I can’t see the declaration in the code.