Java Collections unmodifiableCollection()

unmodifiableCollection() 用于获取指定集合的​​不可修改视图。如果尝试直接或通过其迭代器修改返回的集合,则将导致UnsupportedOperationException异常。

1 语法

public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c)  

2 参数

c:它是要返回其不可修改视图的集合。

3 返回值

返回指定集合的修改视图。

4 unmodifiableCollection()示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        Collections.addAll(c, "Google", "Mozila FireFox", "Yahoo");
        Collection<String> c2 = Collections.unmodifiableCollection(c);
        System.out.println("Unmodifiable Collection: " + c2);
        c.add("Safari");
        System.out.println("Unmodifiable Collection after adding element to the original one:");
        System.out.println(c2);
    }
}

输出结果为:

Unmodifiable Collection: [Google, Mozila FireFox, Yahoo]
Unmodifiable Collection after adding element to the original one:
[Google, Mozila FireFox, Yahoo, Safari]

5 unmodifiableCollection()示例2

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        Collection<String> c = new ArrayList<>();
        Collections.addAll(c, "Google", "Mozila FireFox", "Yahoo");
        System.out.println("Initial Collection: "+ c);
        Collection<String> c2 = Collections.unmodifiableCollection(c);
        c2.add("Safari");
    }
}

输出结果为:

Initial Collection: [Google, Mozila FireFox, Yahoo]
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
	at com.yiidian.Demo.main(Demo.java:18)

6 unmodifiableCollection()示例3

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        Collection<Integer> coll = new ArrayList<>();
        coll.add(10);
        coll.add(20);
        coll.add(30);
        coll.add(40);
        Collection<Integer> coll2 = Collections.unmodifiableCollection(coll);
        System.out.println("Unmodifiable collection: " + coll2);
        coll.add(50);
        System.out.print("Unmodifiable collection after adding (50): "+coll);
    }
}

输出结果为:

Unmodifiable collection: [10, 20, 30, 40]
Unmodifiable collection after adding (50): [10, 20, 30, 40, 50]

 

热门文章

优秀文章