I want to iterate through the values of a Hashtable, which has a large amount of data (apx. 1 GB). For that, I am using:
Hashtable<String,Object> myHashtable = new Hashtable<String,Object>;
// Fill the Hashtable here...
// Get the values as a Collection:
Collection<Object> myValues = myHashtable.values();
// Get the values as an array:
ArrayList<Object> myArray = myValues.toArray();
// Iterate through the values here...
So, my question is: Am I multiplying the data stored? Does I have 3 copies of the same values stored in RAM (one copy in the Hashtable, one copye in the Collection, and one copy in the ArrayList)?
If the answer is yes, I copied the data, is there a way to iterate through the values of the Hashtable without duplicating the data?
If the answer is no, then does that mean the Collection stores pointers? In that case, if I modify the data in the Hashtable after having created the Collection, does the Collection reflect that change? (same question for the ArrayList).
Thanks!
The
values()method does not duplicate data, as per the documentation, it returns a view of the values in the map – meaning: if you change the elements inmyValuesthen the changes will be reflected on the original map.On the other hand,
toArray()does duplicate data, (and it returns an array, not anArrayListas implied by your code) because it creates a new array with a shallow copy of the elements inmyValues. Also, because the array holds references to the elements in the original map, if the objects are mutable changes on them will be reflected on the map – but if you modify the array itself (say, setting to null one of its elements) that change won’t be reflected on the map.The simplest way to iterate through the values of a map without creating additional copies of them is to use an iterator on the values:
And remember, because the values in the map, the contents of
myValuesand the contents ofmyArrayare all references to the same objects, any change you make on them will be reflected on the others as well (assuming they’re mutable.)