HashSet is a collection in Java that stores unique elements only. It does not maintain insertion order and allows fast operations using hashing.
null valueHashSet belongs to the java.util package and implements the Set interface. It is commonly used when duplicates are not allowed.
// Importing HashSet class
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
// Creating a HashSet of Strings
HashSet cities = new HashSet<>();
// Adding elements to HashSet
cities.add("Delhi");
cities.add("Mumbai");
cities.add("Chennai");
cities.add("Delhi");
// Printing HashSet
System.out.println(cities);
}
}
The output will show city names without duplicates. Even though "Delhi" was added twice, it appears only once because HashSet does not allow duplicate values.
Type a value and press Add. Try adding the same value twice to see how HashSet rejects duplicates!
LinkedHashSet if insertion order is requiredcontains()