Java Collections unmodifiableNavigableSet()

unmodifiableNavigableSet() 用于获取指定NavigableSet的不可修改视图。

1 语法

public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)  

2 参数

s:这是要返回其不可修改视图的NavigableSet。

3 返回值

返回指定NavigableSet的不可修改视图。

4 unmodifiableNavigableSet()示例1

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        NavigableSet<Integer> set = new TreeSet<>();
        Collections.addAll(set, 1,2,3,4,5);
        System.out.println("Initial Set: " + set);
        NavigableSet<Integer> set2 = Collections.unmodifiableNavigableSet(set);
        System.out.println("Unmodifiable Navigable Set: " + set2);
        //Modifying the original set
        set.add(15);
        System.out.println("Unmodifiable Navigable Set: " + set2);
    }
}

输出结果为:

Initial Set: [1, 2, 3, 4, 5]
Unmodifiable Navigable Set: [1, 2, 3, 4, 5]
Unmodifiable Navigable Set: [1, 2, 3, 4, 5, 15]

5 unmodifiableNavigableSet()示例2

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        NavigableSet<String> set = new TreeSet<>();
        Collections.addAll(set, "Google", "Facebook", "Instagram");
        System.out.println("Initial Set: " + set);
        NavigableSet<String> set2 = Collections.unmodifiableNavigableSet(set);
        System.out.println("Unmodifiable Navigable Set: " + set2);
        //Modifying the original set
        set.add("Twitter");
        System.out.println("Unmodifiable Navigable Set: " + set2);
    }
}

输出结果为:

Initial Set: [Facebook, Google, Instagram]
Unmodifiable Navigable Set: [Facebook, Google, Instagram]
Unmodifiable Navigable Set: [Facebook, Google, Instagram, Twitter]

6 unmodifiableNavigableSet()示例3

package com.yiidian;

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

public class Demo {

    public static void main(String[] args) {
        NavigableSet<Integer> set = new TreeSet<>();
        Collections.addAll(set, 11, 13, 17);
        System.out.println("Original Set: " + set);
        NavigableSet<Integer> set2 = Collections.unmodifiableNavigableSet(set);
        set2.add(19);
    }
}

输出结果为:

Original Set: [11, 13, 17]
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableCollection.add(Collections.java:1055)
	at com.yiidian.Demo.main(Demo.java:18)

 

热门文章

优秀文章