Java Collections synchronizedSortedSet()方法及示例
java.util.Collections 类的 synchronizedSortedSet() 方法用于返回一个由指定的排序集支持的同步(线程安全)的排序集。为了保证串行访问,对支持的排序集的所有访问都是通过返回的排序集(或其视图)完成的,这一点至关重要。
语法
public static <T> SortedSet<T>
synchronizedSortedSet(SortedSet<T> s)
参数: 该方法将排序后的集合作为参数,被 “包裹 “在一个同步排序的集合中。
返回值: 该方法返回指定排序集的同步视图。
下面是说明synchronizedSortedSet()方法的例子
例1 :
// Java program to demonstrate
// synchronizedSortedSet() method
// for <String> Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of SortedSet<String>
SortedSet<String> set = new TreeSet<String>();
// populate the set
set.add("A");
set.add("B");
set.add("C");
set.add("D");
// printing the Collection
System.out.println("Sorted Set : " + set);
// create a synchronized sorted set
SortedSet<String>
sorset = Collections
.synchronizedSortedSet(set);
// printing the set
System.out.println("Sorted set is : "
+ sorset);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
Sorted Set : [A, B, C, D]
Sorted set is : [A, B, C, D]
例2 :
// Java program to demonstrate
// synchronizedSortedSet() method
// for <Integer> Value
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of SortedSet<String>
SortedSet<Integer>
set = new TreeSet<Integer>();
// populate the set
set.add(10);
set.add(20);
set.add(30);
set.add(40);
// printing the Collection
System.out.println("Sorted Set : " + set);
// create a synchronized sorted set
SortedSet<Integer>
sorset = Collections
.synchronizedSortedSet(set);
// printing the set
System.out.println("Sorted set is : "
+ sorset);
}
catch (IllegalArgumentException e) {
System.out.println("Exception thrown : " + e);
}
}
}
输出。
Sorted Set : [10, 20, 30, 40]
Sorted set is : [10, 20, 30, 40]