当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Collections synchronizedSortedMap()用法及代码示例


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

用法:

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

参数:此方法将排序后的映射图作为参数在同步排序后的映射图中作为“wrapped”。


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

以下示例说明了synchronizedSortedMap()方法

示例1:

// Java program to demonstrate 
// synchronizedSortedMap() method 
// for <String, String> Value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of SortedMap<String, String> 
            SortedMap<String, String> 
                map = new TreeMap<String, String>(); 
  
            // 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<String, String> 
                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 <Integer, Boolean> Value 
  
import java.util.*; 
  
public class GFG1 { 
    public static void main(String[] argv) 
        throws Exception 
    { 
  
        try { 
  
            // creating object of SortedMap<Integer, Boolean> 
            SortedMap<Integer, Boolean> 
                map = new TreeMap<Integer, Boolean>(); 
  
            // 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<Integer, Boolean> 
                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}


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 Collections synchronizedSortedMap() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。