提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
创建不可修改的集合
// 来 自 时 代 J a v a - N o w J a v a . c o m //package com.nowjava; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; public class Main { public static void main(String[] argv) { Collection c = java.util.Arrays.asList("asdf", "nowjava.com"); System.out.println(unmodifiableCollection(c));/*来自 n o w j a v a . c o m - 时代Java*/ } /** * @return an <b>UNMODIFIABLE</b> Collection<T> */ public static <T> Collection<T> unmodifiableCollection( final Collection<? extends T> c) { return (c == null) ? Collections.<T> emptyList() : Collections .unmodifiableCollection(c); } public static <T> List<T> asList(final Iterable<? extends T> iterable) { return (iterable instanceof Collection) ? new LinkedList<T>( (Collection<? extends T>) iterable) : new LinkedList<T>() { private static final long serialVersionUID = 3109256773218160485L; { if (iterable != null) { for (final T t : iterable) { add(t); } } } }; }