Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to create a new HashSet or to reuse after invoking hashSet.clear()

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?

like image 474
wings Avatar asked Aug 29 '13 11:08

wings


People also ask

How to copy or append HashSet to another HashSet in Java?

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.

Should I use HashSet or List for hashing?

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)).

What is the difference between HashSet and HashMap?

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.

What are the important points about Java HashSet class?

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.


1 Answers

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.

like image 190
Uwe Plonus Avatar answered Nov 14 '22 22:11

Uwe Plonus