Java Collections emptyList()

emptyList() 获取没有元素的List。这些空List本质上是不可变的。

1 语法

public static final <T> List<T> emptyList()  

2 参数

3 返回值

返回一个不可变的空List。

4 Collections emptyList()示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create an empty List
        List<String> EmptyList = Collections.<String>emptyList();
        System.out.println("Empty list: "+EmptyList);
    }
}

输出结果为:

Empty list: []

5 Collections emptyList()示例2

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create an empty List
        List<String> emptylist = Collections.emptyList();
        System.out.println("Created empty immutable list: "+emptylist);
        //Try to add elements
        emptylist.add("A");
        emptylist.add("B");
    }
}

输出结果为:

Created empty immutable list: []
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at com.yiidian.Demo.main(Demo.java:18)

6 Collections emptyList()示例3

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        //Create an empty List
        List<Integer> empList = Collections.emptyList();
        empList.add(1);
        empList.add(2);
        System.out.println("Created empty immutable List: "+empList);
    }
}

输出结果为:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.add(AbstractList.java:148)
	at java.util.AbstractList.add(AbstractList.java:108)
	at com.yiidian.Demo.main(Demo.java:16)

 

热门文章

优秀文章