In java.util.Collections class, synchronizedSet() method is used to return a synchronized (thread-safe) set backed by the specified set. This method takes the HashSet as a parameter. To guarantee serial access, it is critical that all access to the backing set is accomplished through the returned set. The task is to get the synchronized set from a given HashSet.
Input : HashSet = [3, 4, 5] Output: synchronizedSet = [3, 4, 5] Input : HashSet = ['a', 'b', 'c'] Output: synchronizedSet = ['a', 'b', 'c']
public static <T> Set<T> synchronizedSet(Set<T> s)
Parameters: HashSet as a parameter to be “wrapped” in a synchronized set.
Return Value: Synchronized view of the specified set.
- Create a HashSet.
- Add some elements in the HashSet.
- Create a Set variable and assign it with the Collections.synchronizedSet() method.
- Print the new synchronized Set.
Below is the implementation of the above approach:
Synchronized Set: [1, 2, 3, 4, 5]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.