Literally shocked. Alright, this kind of feeling is not something I have experienced while working with Java before. Mostly it has been frustration leading me to take a long long break before returning to the code only to find that I was just plain silly. But this is different.
The offending piece of code: (simplified)
Double[] arr = new Double[N];
for (String key : sampleHashMap.keySet()) {
for (int i = 0; i < N; i++) {
arr[i] = get_some_random_value();
}
myHashMap.put(key, arr);
}
When we get to the line for updating arr[i], believe it or not, all values of arr already in myHashMap hashmap get updated!
There is just one double array arr. Every iteration, it gets updated with new values, and somehow, these values are reflected in the myHashMap for all keys which are already stored in there. It is as if all the value mappings in myHashMap, still point to the same address where tfIdfForAllDocs is written.
To solve this, I made sure I am creating a new double array every iteration.
The offending piece of code: (simplified)
Double[] arr = new Double[N];
for (String key : sampleHashMap.keySet()) {
for (int i = 0; i < N; i++) {
arr[i] = get_some_random_value();
}
myHashMap.put(key, arr);
}
When we get to the line for updating arr[i], believe it or not, all values of arr already in myHashMap hashmap get updated!
There is just one double array arr. Every iteration, it gets updated with new values, and somehow, these values are reflected in the myHashMap for all keys which are already stored in there. It is as if all the value mappings in myHashMap, still point to the same address where tfIdfForAllDocs is written.
To solve this, I made sure I am creating a new double array every iteration.
for (String key : sampleHashMap.keySet()) {
Double[] arr = new Double[N];
for (int i = 0; i < N; i++) {
arr[i] = get_some_random_value();
}
myHashMap.put(key, arr);
}
When you do put operation on hashmap, the value that you are giving to the function, a copy of the value is NOT getting stored in the hashmap. Just the reference of the original value!
0 comments:
Post a Comment