Site icon

What is HashSet collection in java (class hierarchy & example)

1. What is HashSet collection in java?

  1. HashSet class implements the Set interface, backed by a hash table.
  2. HashSet contains the unique elements.
    • HashSet does not contains any duplicate keys
    • HashSet can have only 1 null key.
  3. HashSet does not maintained the order of elements or keys.
  4. HashSet is UnSynchronized and not thread safe.
  5. 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.
  6. HashSet offers constant time performance for the basic operations like add, remove, contains and size.

2. HashSet collection class hierarchy:

Fig 1: 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)

HashSet collection - Unique sports list:
[null, Tennis, Cricket, Golf, Basketball, Boxer]
Exit mobile version