创建一个不可修改的Set

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class CreateUnmodifiableSet {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(set());
}
public static  Set set(final T... elements) {
    final HashSet set = new HashSet(elements.length);
    Collections.addAll(set, elements);
    return Collections.unmodifiableSet(set);
}

public static  Set set() {
    return new HashSet();
}

/**
 * @return an UNMODIFIABLE Set<T>
 */
public static  Set unmodifiableSet(final Set s) {
    return (s == null) ? Collections. emptySet() : Collections
            .unmodifiableSet(s);
}

}
Console:
[]

你可能感兴趣的:(创建一个不可修改的Set)