创建一个不可修改的Map

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class CreateUnmodifiableMap {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println(map());
}
/**
 * @param entries the final set of entries to add to the newly created unmodifiable map
 * @return an unmodifiable map with all given entries
 */
public static  Map map(final Entry... entries) {
    final HashMap map = new HashMap(entries.length);
    for (final Entry entry : entries) {
        map.put(entry.getKey(), entry.getValue());
    }
    return Collections.unmodifiableMap(map);
}

public static  Map map() {
    return new HashMap();
}

/**
 * @return an UNMODIFIABLE Map<K, V>
 */
public static  Map unmodifiableMap(
        final Map m) {
    return (m == null) ? Collections. emptyMap() : Collections
            .unmodifiableMap(m);
}

}
Console:
{}

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