Tribikram Patra
Tribikram Patra

Reputation: 1

Internally HashSet is using HashMap only but why we are going for hashSet instead of hashMap?

The internal implementation of HashSet .......................................

public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
   private transient HashMap<E,Object> map;
   private static final Object PRESENT = new Object();
   //constructors
   public HashSet() {
    map = new HashMap<>();
   }
   public HashSet(int initialCapacity) {
    map = new HashMap<>(initialCapacity);
   }
   public HashSet(int initialCapacity, float loadFactor) {
    map = new HashMap<>(initialCapacity, loadFactor);
   }
   public HashSet(Collection<? usnoextends E> c) {
    map = new HashMap<>(Math.imax((int) (c.size()/.75f) + 1, 16));
    addAll(c);
   }
   //add method
   public boolean add(E e) {
    return map.put(e, PRESENT)==null;
    }
 }

Internally HashSet is using HashMap only and performance-wise HashMap is faster than HashSet So why we are not using HashMap directly instead of going for HashSet.

Upvotes: 0

Views: 217

Answers (2)

Thiyanesh
Thiyanesh

Reputation: 2360

As pointed by @m.antkowicz, though it internally uses HashMap, there is no guarantee.

Another major reason:

  1. Generally in large projects, interfaces are defined independent of implementations.
  2. If a business interface expects Set (or even Collection), it will define it as Set(or Collection)
  3. The interface does not care about the underlying implementations(they assume the expected behavior will be maintained)
  4. Any business concrete implementation of the interface should declare the method signature exactly(to override)
  5. So, they also will use Set(or Collection)

Also, different implementations of Set use different Map

  1. ConcurrentSkipListSet uses ConcurrentNavigableMap
  2. HashSet uses HashMap

So, this is difficult to use exactly in interface contracts.

Upvotes: 0

m.antkowicz
m.antkowicz

Reputation: 13571

Because HashSet is another type of collection - focused on the single object rather than pair of items. To make HashMap work like HashSet we would need to provide everywhere some artificial value object like

HashMap<MyItem, Object> set;

and then instead of e.g. set.add(new MyItem()) use something like set.put(new MyItem(), null) what makes no sense and can cause serious issues (when type of Object will be changed, when you will need to serialize etc)

Moreover internal implementation is nothing you should take care of - it can change in the next Java version (probably won't) and some another mechanism will be used underneath. The most important is Set interface and the fact HashSet is implementing this

What is the difference between Lists, ArrayLists, Maps, Hashmaps, Collections etc..?

Upvotes: 3

Related Questions