📜  Java中的集合 synchronizedSortedMap() 方法及示例

📅  最后修改于: 2022-05-13 01:55:28.386000             🧑  作者: Mango

Java中的集合 synchronizedSortedMap() 方法及示例

Java.util.Collections类的synchronizedSortedMap()方法用于返回由指定排序映射支持的同步(线程安全)排序映射。为了保证串行访问,对后备排序映射的所有访问都是通过返回的排序映射(或其视图)完成的,这一点至关重要。

句法:

public static  SortedMapK, V>
  synchronizedSortedMap(SortedMapK, V> m)

参数:此方法将排序后的地图作为参数“包装”在同步的排序地图中。

返回值:此方法返回指定排序地图的同步视图

以下是说明synchronizedSortedMap()方法的示例

示例 1:

// Java program to demonstrate
// synchronizedSortedMap() method
// for  Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of SortedMap
            SortedMap
                map = new TreeMap();
  
            // populate the map
            map.put("1", "A");
            map.put("2", "B");
            map.put("3", "C");
  
            // printing the Collection
            System.out.println("Sorted Map : " + map);
  
            // create a sorted map
            SortedMap
                sortedmap = Collections
                                .synchronizedSortedMap(map);
  
            // printing the map
            System.out.println("Synchronized sorted map is :"
                               + sortedmap);
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
Sorted Map : {1=A, 2=B, 3=C}
Synchronized sorted map is :{1=A, 2=B, 3=C}

示例 2:

// Java program to demonstrate
// synchronizedSortedMap() method
// for  Value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of SortedMap
            SortedMap
                map = new TreeMap();
  
            // populate the map
            map.put(100, true);
            map.put(200, true);
            map.put(300, true);
  
            // printing the Collection
            System.out.println("Sorted Map : " + map);
  
            // create a sorted map
            SortedMap
                sortedmap = Collections
                                .synchronizedSortedMap(map);
  
            // printing the map
            System.out.println("Synchronized sorted map is :"
                               + sortedmap);
        }
  
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
Sorted Map : {100=true, 200=true, 300=true}
Synchronized sorted map is :{100=true, 200=true, 300=true}