How to Get a Synchronized Set of HashSet in Java


This example aims to get a synchronized set from HashSet in Java.

Source Code

package com.beginner.examples;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class GetSynchronizedSetExamples {

	
	public static void main(String[] args) {
		
		HashSet hs = new HashSet();
		
		//Get synchronized set
		Set synSet = Collections.synchronizedSet(hs);
		
		//This set cannot store the same elements
		synSet.add("a");
		synSet.add("b");
		synSet.add("c");
		synSet.add("a");
		
		System.out.println(synSet);

	}

}

Output:

[b, c, a]

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments