What is HashSet collection in java (class hierarchy & example)
Yogesh
1. What is HashSet collection in java?
HashSet class implements the Set interface, backed by a hash table.
HashSet contains the unique elements.
HashSet does not contains any duplicate keys
HashSet can have only 1 null key.
HashSet does not maintained the order of elements or keys.
HashSet is UnSynchronized and not thread safe.
Iterator of HashSet is fail-fast.
Iterator will throw ConcurrentModificationException, if HashSet modified at any time after the iterator is created, in any way except through the iterator’s own remove method.
HashSet offers constant time performance for the basic operations like add, remove, contains and size.
2. HashSet collection class hierarchy:
3. Program – hashset collection having String objects in java (example)
package org.learn.collection.set.hset;
import java.util.HashSet;
import java.util.Set;
public class DemoHashSet {
public static void main(String[] args) {
Set<String> setSports = new HashSet<>();
setSports.add("Tennis");
setSports.add("Cricket");
setSports.add("Tennis");
setSports.add(null);
setSports.add("Basketball");
setSports.add("Cricket");
setSports.add(null);
setSports.add("Basketball");
setSports.add("Golf");
setSports.add("Boxer");
System.out.println("HashSet collection - Unique sports list:\n"+ setSports);
}
}
4. Output – hashset collection having String objects in java (example)