Thursday, 7 September 2017

Set Implementation in Java


  • Set conatins only unique elements.
  • HashSet achieves uniqueness of its elements by using hashmap
  • Whenever we create an object of hashset inernally it will create an object of hashmap.
  • If we add an element into a set it will store as key for map. But same time we need a value for key. That value can be Object instance.So whenever we add an element to set it will create Hash map entry with key as added element and value as DUMMY Object.
  • There are two possible output we will get we put an entry into a hashmap
    1. null: If the Key is unique and succussfully added to tha map. 2. Old Value of the Key: If the key is duplicate
      SkHashSet.java
package com.sk.custom_hashset; import java.util.HashMap; import java.util.Set; public class SkHashSet { private HashMap MAP = new HashMap(); private static final Object DUMMY = new Object(); public boolean add(E element) { return MAP.put(element, DUMMY) == null; } public int size() { return MAP.size(); } public Set getAll() { return MAP.keySet(); } }
Download Source

No comments:

Post a Comment

Search This Blog

Contact us

Name

Email *

Message *