TIL : HashSet

adamsteradam·2022년 9월 27일

I believe in practicing algorithm is crucial for understanding the language. After spending some time of agony from facing an unsolvable problem, I had no option but to negotiate with myself to look up the answer.

I was shocked to see how concise the answer was and it used a method I have never used before, the HashSet.

So what is a HashSet?

According to the Oracle documentation, Class HashSet implements the Set interface, backed by a hash table. It does not guarantee that the order will remain constant over time.
As it implements the Set Interface, duplicate values are not allowed
Also implements Serializable and Cloneable interfaces. HashSet not only stores unique Objects but also a unique Collection of Objects like ArrayList<E>, LinkedList<E>,Vector<E>.


import java.util.HashSet;
public class Example {
   public static void main(String[] args){
      HashSet<String> hs = new HashSet<String>();



Since it does not allow any duplicate value, the second Adam does not get to be in the set.

When to use?

For me personally, if I have to filter out all the duplicate integers in an integer array, I was able to solve the problem using HashSet. Utilizing HashSet on any problem related to unique value would be beneficial.


Difference between HashSet and HashMap

There is also a class called HashMap. They seemed to function similarly but there are some differences.

  1. HashMap implements Map Interface.
  2. HashMap store key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
  3. Therefore, requires two objects put to add an element to the HashMap object. (key, value pair)
  4. HashMap is faster than HashSet.
  5. HashMap uses put() method rather than add().

0개의 댓글