Java Collections emptyMap()

emptyMap() 返回一个不变的空Map。

1 语法

public static final <K,V> Map<K,V> emptyMap()  

2 参数

3 返回值

返回一个不变的空Map。

4 Collections emptyMap()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.emptyMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create an empty Map
        Map<String,String> EmptyMap = Collections.emptyMap();
        System.out.println("Created Empty Map: "+EmptyMap);
    }
}

输出结果为:

Created Empty Map: {}

5 Collections emptyMap()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.emptyMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create an empty Map
        Map<String,String> EmptyMap = Collections.emptyMap();
        System.out.println("Created Empty Map: "+EmptyMap);
        // try to add elements
        EmptyMap.put("1","from yiidian.com");
    }
}

输出结果为:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractMap.put(AbstractMap.java:209)
	at com.yiidian.Demo.main(Demo.java:18)
Created Empty Map: {}

6 Collections emptyMap()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.emptyMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create an empty Map
        Map<Integer, Integer> empMap = Collections.emptyMap();
        empMap.put(1, 23424);
        empMap.put(2, 65776);
        System.out.println("Created empty immutable Map: "+empMap);
    }
}

输出结果为:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractMap.put(AbstractMap.java:209)
	at com.yiidian.Demo.main(Demo.java:16)

 

热门文章

优秀文章