HashSet in java
In this previous post, we have seen how to Iterate over a Vector. In this post, we will learn about HashSet in java.
HashSet has the following features.
- HashSet implements Set interface.
- It does not maintain any insertion order. Elements would be returned in any random order.
- Allows only unique value. If we try to add duplicate elements, then old value will be overwritten.
- HashSet is non-synchronized.
- HashSet allows null values however if you insert more than one nulls it would still return only one null value.
Syntax:
HashSet<ObjectType> name = new HashSet<ObjectType>();
Example:
import java.util.HashSet; public class HashSetExample { public static void main(String[] args) { HashSet<String> cars = new HashSet<String>(); cars.add("BMW"); cars.add("Honda"); cars.add("Ferrari"); cars.add("Bugatti"); cars.add("Mercedes"); //Add duplicate elements cars.add("Ferrari"); cars.add("BMW"); //Addition of null values cars.add(null); cars.add(null); //Display the hashset System.out.println("HashSet : "+cars); } }
Output:
HashSet : [null, Bugatti, BMW, Ferrari, Honda, Mercedes]
HashSet Methods:
- boolean add(Element e): It adds the element e to the HashSet.
- void clear(): It removes all the elements from the Set.
- Object clone(): This method returns a shallow copy of the HashSet.
- 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.
- boolean isEmpty(): Returns true if there is no element present in the Set.
- int size(): It gives the number of elements of a Set.
- boolean remove(Object o): It removes the specified Object o from the Set.