HashSet:

  • The HashSet class implements the Set interface. It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. \

  • HashSet doesn’t allow duplicates. If you try to add a duplicate element in HashSet, the old value would be overwritten.

  • HashSet allows null values however if you insert more than one nulls it would still return only one null value.

HashSet Methods:

1. boolean add(Element e): It adds the element e to the list. 2. void clear(): It removes all the elements from the lis .

3. Object clone(): This method returns a shallow copy of the HashSet.

4. boolean contains(Object o): It checks whether the specified Object o is present in the list or not. If the object has been found it returns true else false.

5. boolean isEmpty(): Returns true if there is no element present in the Set.

6. int size(): It gives the number of elements of a Set.

7. boolean(Object o): It removes the specified Object o from the Set.

Output:

[Java, Selenium, QTP]

Is HashSet empty? false [Selenium, QTP]

Size of the HashSet: 2

Does HashSet contains first element? False

How to Iterate over a Set/HashSe

t Below example shows how to read all elements from the HashSet objects. You can iterate through HashSet by getting Iterator object. By calling iterator() method, you can get Iterator object.

Output:

Java

Selenium

QTP

Last updated