/** * Returns the empty map (immutable). This map is serializable. * * <p>This example illustrates the type-safe way to obtain an empty set: * <pre> * Map<String,Date> s = Collections.emptyMap(); * </pre> * Implementation note: Implementations of this method need not * create a separate <tt>Map</tt> object for each call. Using this * method is likely to have comparable cost to using the like-named * field. (Unlike this method,the field does not provide type safety.) * * @see #EMPTY_MAP * @since 1.5 */ @SuppressWarnings("unchecked") public static final <K,V> Map<K,V> emptyMap() { return (Map<K,V>) EMPTY_MAP; }
public static final Map EMPTY_MAP = new EmptyMap<>();
EmptyMap类如下
/** * @serial include */ private static class EmptyMap<K,V> extends AbstractMap<K,V> implements Serializable { private static final long serialVersionUID = 6428348081105594320L; public int size() {return 0;} public boolean isEmpty() {return true;} public boolean containsKey(Object key) {return false;} public boolean containsValue(Object value) {return false;} public V get(Object key) {return null;} public Set<K> keySet() {return emptySet();} public Collection<V> values() {return emptySet();} public Set<Map.Entry<K,V>> entrySet() {return emptySet();} public boolean equals(Object o) { return (o instanceof Map) && ((Map<?,?>)o).isEmpty(); } public int hashCode() {return 0;} // Preserves singleton property private Object readResolve() { return EMPTY_MAP; } }
这种类和实用方法的用途是什么?我试过了
Map myMap = Collections.emptyMap(); myMap.put("Name","John");
我在线程“main”java.lang.UnsupportedOperationException中得到异常
因为收藏是不可变的,不支持修改.那么这样的数据结构使用什么呢?
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。