I want to process some new data in a HashSet, without any old data needed or the old HashSet object. The old HashSet object isn't referred to elsewhere.
Is it better to simply do hashset = new HashSet<String>()
and let JVM to free the memory of the old HashSet object or should I call hashSet.clear()
and reuse the same HashSet?
According to openJDK, hashSet.clear() is:
public void clear() {
map.clear();
}
and map.clear() :
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
Since map.clear() iterates all the entries, will it be time consuming when the hashSet is large? Which one is recommended in this case, the constructor method or the clear() method?
We can use the addAll () method to copy or to append a HashSet to a another HashSet. addAll method in Java add all elements to the HashSet. Note: The order of elements may be the same or may not be the same.
If you don't, use a HashSet. Let Microsoft worry about the implementation of their hashing algorithms and objects. A HashSet will access items without having to enumerate the collection (complexity of O (1) or near it), and because a List guarantees order, unlike a HashSet, some items will have to be enumerated (complexity of O (n)).
The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means that the class does not guarantee the constant order of elements over time. This class permits the null element.
The important points about Java HashSet class are: HashSet stores the elements by using a mechanism called hashing. HashSet contains unique elements only. HashSet allows null value.
Simple don't reference your HashSet
anymore and let the garbage collector do the work.
Clearing the HashSet
before dereferencing it does not free the memory any faster.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With