DEV Community

velvizhi Muthu
velvizhi Muthu

Posted on

Module 5-Hashset

01.What is set?
Set is interface in java.util package.
We can't create an object directly.
Stores only unique elements (no duplicates)

02. What are the main implementation of set?
HashSet
LinkedHashSet
TreeSet

03.What is Hashset?

  1. HashSet is a class
  2. HashSet is a Java.util package.
  3. HashSet stores the elements by using a mechanism called hashing.
  4. HashSet contains unique elements only.
  5. HashSet allows null value.
  6. HashSet class is non synchronized.
  7. HashSet doesn't maintain the insertion order.
  8. HashSet does not allows duplicate elements.

04.What are the method of the HashSet?

1.Add (E e)
Adds the specified element to this set if it is not already present.
Boolean modified and type.

2.Clear()
Removes all of the elements from this set.

3.Clone()
Returns a shallow copy of this HashSet instance, the elements themselves are not cloned.

4.Contain()
Returns true if this set contains the specified element.

5.isEmpty()
Returns true if this set contains no elements.

6.remove(Object o)
Removes the specified element from this set if it is present.

7.size()
Returns the number of elements in this set .

8.spliterator()
Creates a late-binding and fail-fast Spliterator over the elements in this set.

9.iterator()
Returns an iterator over the elements in this set.

10.Addall();
The method addAll(Collection) in the type AbstractCollection is not applicable for the arguments (int)

11.get()
The method get(int) is undefined for the type HashSet

12.removeAll()
The method removeAll(Collection) in the type AbstractSet is not applicable for the arguments (String).

05. When Should You Use a HashSet?

  • You want to avoid duplicates.
  • You need fast lookup and removal.
  • You don't care about the order of elements.

06. Why Use HashSet in Java?

  1. To Store Unique Values
  2. HashSet automatically eliminates duplicates.
  • If you try to add the same element again, it will not be added.
  1. Fast Performance
  2. No Insertion Order Guarantee
  3. Null Elements-allow one null value.

07.Disadvantages of HashSet in Java?
1.HashSet does not maintain insertion orde
2.You can add only one null element.

Top comments (0)