加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么我们有不可变的空地图?

发布时间:2020-12-14 05:31:32 所属栏目:Java 来源:网络整理
导读:/** * Returns the empty map (immutable). This map is serializable. * * pThis example illustrates the type-safe way to obtain an empty set: * pre * Maplt;String,Dategt; s = Collections.emptyMap(); * /pre * Implementation note: Implementatio
/**
 * Returns the empty map (immutable).  This map is serializable.
 *
 * <p>This example illustrates the type-safe way to obtain an empty set:
 * <pre>
 *     Map&lt;String,Date&gt; 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中得到异常
因为收藏是不可变的,不支持修改.那么这样的数据结构使用什么呢?

解决方法

What is the use of such Class and utility method?

如果您返回地图结果,通常它是不可变的,例如,您可以创建一个不可变的地图,包裹您自己的“真实”数据,而不必创建完整的副本,或信任呼叫者不要变异

另外,如果你返回一个空的地图结果,那么每次都不需要创建一个新的对象就很方便 – 每个空的地图都等于每一个空的地图,所以使用一个实例是很好的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读