Java Collections unmodifiableList()
unmodifiableList() 用于获取指定列表的不可修改视图。如果尝试直接或通过其迭代器修改返回的列表,则将导致UnsupportedOperationException。
1 语法
public static <T> List<T> unmodifiableList(List<? extends T> list)
2 参数
list:要返回不可修改视图的列表。
3 返回值
返回指定列表的修改视图。
4 unmodifiableList()示例1
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableList的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "Google", "Mozila FireFox", "Yahoo");
List<String> list2 = Collections.unmodifiableList(list);
System.out.println("Unmodifiable List: " + list2);
list.add("Safari");
System.out.print("Unmodifiable List after adding element to the list:");
System.out.println(list2);
}
}
输出结果为:
Unmodifiable List: [Google, Mozila FireFox, Yahoo]
Unmodifiable List after adding element to the list:[Google, Mozila FireFox, Yahoo, Safari]
5 unmodifiableList()示例2
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableList的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
Collections.addAll(list, "Google", "Mozila FireFox", "Yahoo");
List<String> list2 = Collections.unmodifiableList(list);
System.out.println("Unmodifiable List: " + list2);
list2.add("Safari");
}
}
输出结果为:
Unmodifiable List: [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 unmodifiableList()示例3
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* Java Collections.unmodifiableList的例子
*/
import java.util.*;
public class Demo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
List<Integer> list2 = Collections.unmodifiableList(list);
System.out.println("Unmodifiable list: " + list2);
list.add(50);
System.out.println("Unmodifiable list after adding (50): "+list);
}
}
输出结果为:
Unmodifiable list: [10, 20, 30, 40]
Unmodifiable list after adding (50): [10, 20, 30, 40, 50]
热门文章
优秀文章