Home » Java programming language

Java Collections synchronizedSet() Method with Example

Collections Class synchronizedSet() method: Here, we are going to learn about the synchronizedSet() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on February 07, 2020

Collections Class synchronizedSet() method

  • synchronizedSet() method is available in java.util package.
  • synchronizedSet() method is used to return the synchronized view of the given set (set).
  • synchronizedSet() method is a static method, it is accessible with the class name and if we try to access the method with the class object then also we will not get any error.
  • synchronizedSet() method does not throw an exception at the time of returning the synchronized set.

Syntax:

    public static Set synchronizedSet(Set set);

Parameter(s):

  • Set set – represents the set to be viewed in synchronized set.

Return value:

The return type of this method is Set, it returns synchronized view of the given set.

Example:

// Java program to demonstrate the example 
// of Set synchronizedSet() method of Collections

import java.util.*;

public class SynchronizedSetOfCollections {
    public static void main(String args[]) {
        // Instantiates a set object
        Set < Integer > set = new HashSet < Integer > ();

        // By using add() method is to add
        //objects in a hash set 
        set.add(10);
        set.add(20);
        set.add(30);
        set.add(40);
        set.add(50);

        // Display HashSet
        System.out.println("HashSet: " + set);

        // By using SynchronizedSet() method is to
        // represent the hash set in synchronized view
        set = Collections.synchronizedSet(set);

        // Display Synchronized HashSet
        System.out.println("Collections.synchronizedSet(set): " + set);
    }
}

Output

HashSet: [50, 20, 40, 10, 30]
Collections.synchronizedSet(set): [50, 20, 40, 10, 30]


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.