Java.util.Collections 类

java.util.Collections.synchronizedNavigableMap() 方法返回由指定支持的同步(线程安全)可导航map导航map。

语法

public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)

这里,K和V分别是导航map维护的键和值的类型。

参数

m 指定要"包装"在同步可导航map中的可导航map。

返回值

返回指定可导航map的同步视图。

异常

无。

示例:

在下面的示例中,java.util.Collections.synchronizedNavigableMap() 方法返回给定可导航map的同步视图。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建一个NavigableMap对象
    NavigableMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //填充MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");

    //打印map
    System.out.println("MyMap contains: " + MyMap); 

    //创建可导航map的同步视图
    NavigableMap NewMap = Collections.synchronizedNavigableMap(MyMap);

    //打印同步导航map
    System.out.println("NewMap contains: " + NewMap); 
  }
}

上述代码的输出将是:

MyMap contains: {101=John, 102=Marry, 103=Kim}
NewMap contains: {101=John, 102=Marry, 103=Kim}