當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。