Collections.unmodifiableMap()方法详解

今天在研究java.time.ZoneId时,源码中发现了以下代码:

public abstract class ZoneId implements Serializable {
    public static final Map SHORT_IDS;

    static {
        Map map = new HashMap<>(64);
        map.put("ACT", "Australia/Darwin");
        map.put("AET", "Australia/Sydney");
        map.put("AGT", "America/Argentina/Buenos_Aires");
        map.put("ART", "Africa/Cairo");
        map.put("AST", "America/Anchorage");
        map.put("BET", "America/Sao_Paulo");
        map.put("BST", "Asia/Dhaka");
        map.put("CAT", "Africa/Harare");
        map.put("CNT", "America/St_Johns");
        map.put("CST", "America/Chicago");
        map.put("CTT", "Asia/Shanghai");
        map.put("EAT", "Africa/Addis_Ababa");
        map.put("ECT", "Europe/Paris");
        map.put("IET", "America/Indiana/Indianapolis");
        map.put("IST", "Asia/Kolkata");
        map.put("JST", "Asia/Tokyo");
        map.put("MIT", "Pacific/Apia");
        map.put("NET", "Asia/Yerevan");
        map.put("NST", "Pacific/Auckland");
        map.put("PLT", "Asia/Karachi");
        map.put("PNT", "America/Phoenix");
        map.put("PRT", "America/Puerto_Rico");
        map.put("PST", "America/Los_Angeles");
        map.put("SST", "Pacific/Guadalcanal");
        map.put("VST", "Asia/Ho_Chi_Minh");
        map.put("EST", "-05:00");
        map.put("MST", "-07:00");
        map.put("HST", "-10:00");
        SHORT_IDS = Collections.unmodifiableMap(map);
    }
}

这个方法很眼熟,看单词也能猜到是和不可改变的map有关,这个方法返回一个UnmodifiableMap对象,UnmodifiableMap是Collections的一个静态内部类

public class Collections { {
    public static  Map unmodifiableMap(Map m) {
        return new UnmodifiableMap<>(m);
    }

    private static class UnmodifiableMap implements Map, Serializable {
        public V put(K key, V value) {
            throw new UnsupportedOperationException();
        }

        public V remove(Object key) {
            throw new UnsupportedOperationException();
        }

        public void putAll(Map m) {
            throw new UnsupportedOperationException();
        }

        public void clear() {
            throw new UnsupportedOperationException();
        }
    }
}

看完以上代码就知道为什么是不可修改的map了,UnmodifiableMap实现了Map接口,实现Map的会改变对象的方法时,都抛出UnsupportedOperationException(不支持操作异常)

你可能感兴趣的:(java,开发语言)