memory management - Does Java duplicate data when calling Collection values() on a Hashtable? -
i want iterate through values of hashtable, has large amount of data (apx. 1 gb). that, using:
hashtable<string,object> myhashtable = new hashtable<string,object>; // fill hashtable here... // values collection: collection<object> myvalues = myhashtable.values(); // values array: arraylist<object> myarray = myvalues.toarray(); // iterate through values here... so, question is: multiplying data stored? have 3 copies of same values stored in ram (one copy in hashtable, 1 copye in collection, , 1 copy in arraylist)?
if answer yes, copied data, there way iterate through values of hashtable without duplicating data?
if answer no, mean collection stores pointers? in case, if modify data in hashtable after having created collection, collection reflect change? (same question arraylist).
thanks!
the values() method not duplicate data, per documentation, returns view of values in map - meaning: if change elements in myvalues changes reflected on original map.
on other hand, toarray() does duplicate data, (and returns array, not arraylist implied code) because creates new array shallow copy of elements in myvalues. also, because array holds references elements in original map, if objects mutable changes on them reflected on map - if modify array (say, setting null 1 of elements) change won't reflected on map.
the simplest way iterate through values of map without creating additional copies of them use iterator on values:
for (object val : myhashtable.values()) { // each value } and remember, because values in map, contents of myvalues , contents of myarray references same objects, change make on them reflected on others (assuming they're mutable.)
Comments
Post a Comment