从Java HashSet 获取同步集
在Java.util.Collections类中, synchronizedSet()方法用于返回由指定集合支持的同步(线程安全)集合。此方法将 HashSet 作为参数。为了保证串行访问,对后备集的所有访问都通过返回的集完成是至关重要的。任务是从给定的 HashSet 中获取同步集。
例子:
Input : HashSet = [3, 4, 5]
Output: synchronizedSet = [3, 4, 5]
Input : HashSet = ['a', 'b', 'c']
Output: synchronizedSet = ['a', 'b', 'c']
句法:
public static Set synchronizedSet(Set s)
参数: HashSet 作为要“包装”在同步集中的参数。
返回值:指定集合的同步视图。
方法:
- 创建一个哈希集。
- 在 HashSet 中添加一些元素。
- 创建一个 Set 变量并使用 Collections.synchronizedSet() 方法分配它。
- 打印新的同步集。
下面是上述方法的实现:
Java
// Java code to get synchronized
// set from hash set
import java.util.*;
public class GFG {
public static void main(String args[])
{
// creating hash set
Set hash_set = new HashSet();
// adding the elements to hash set
hash_set.add(1);
hash_set.add(2);
hash_set.add(3);
hash_set.add(4);
hash_set.add(5);
// changing hash set to synchronized
// set and storing in set
Set synset = Collections.synchronizedSet(hash_set);
System.out.println("Synchronized Set: " + synset);
}
}
输出
Synchronized Set: [1, 2, 3, 4, 5]