7

Collections类中有一个方法。

Set<E> Collections.newSetFromMap(<backing map>)

支持地图和地图支持的集合是什么意思?

4

4 回答 4

8

也许看看实现会很有启发性:

private static class SetFromMap<E> extends AbstractSet<E>
    implements Set<E>, Serializable
{
    private final Map<E, Boolean> m;  // The backing map
    private transient Set<E> s;       // Its keySet

    SetFromMap(Map<E, Boolean> map) {
        if (!map.isEmpty())
            throw new IllegalArgumentException("Map is non-empty");
        m = map;
        s = map.keySet();
    }

    public void clear()               {        m.clear(); }
    public int size()                 { return m.size(); }
    public boolean isEmpty()          { return m.isEmpty(); }
    public boolean contains(Object o) { return m.containsKey(o); }
    public boolean remove(Object o)   { return m.remove(o) != null; }
    public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
    public Iterator<E> iterator()     { return s.iterator(); }
    public Object[] toArray()         { return s.toArray(); }
    public <T> T[] toArray(T[] a)     { return s.toArray(a); }
    public String toString()          { return s.toString(); }
    public int hashCode()             { return s.hashCode(); }
    public boolean equals(Object o)   { return o == this || s.equals(o); }
    public boolean containsAll(Collection<?> c) {return s.containsAll(c);}
    public boolean removeAll(Collection<?> c)   {return s.removeAll(c);}
    public boolean retainAll(Collection<?> c)   {return s.retainAll(c);}
    // addAll is the only inherited implementation

    private static final long serialVersionUID = 2454657854757543876L;

    private void readObject(java.io.ObjectInputStream stream)
        throws IOException, ClassNotFoundException
    {
        stream.defaultReadObject();
        s = m.keySet();
    }
}

编辑 - 添加说明:

您提供的地图用作m此对象中的字段。

当您向集合添加元素时,它会向地图e添加一个条目。e -> true

public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }

因此,此类通过简单地忽略事物映射到的值并仅使用键,将您Map变成一个行为类似于 a 的对象。Set

于 2012-11-23T07:23:10.123 回答
5

我刚刚为你做了一个示例代码

HashMap<String, Boolean> map = new HashMap<String, Boolean>();

Set<String> set = Collections.newSetFromMap(map);

System.out.println(set);

for (int i = 0; i < 10; i++)
    map.put("" + i, i % 2 == 0);

System.out.println(map);

System.out.println(set);

和输出

[]
{3=false, 2=true, 1=false, 0=true, 7=false, 6=true, 5=false, 4=true, 9=false, 8=true}
[3, 2, 1, 0, 7, 6, 5, 4, 9, 8]
于 2012-11-23T07:55:05.840 回答
4

简单地说,Collections.newSetFromMap使用提供的Map<E>实现来存储Set<E>元素。

于 2012-11-23T07:42:28.250 回答
0

Set 在内部使用 Map 来存储值。这里的backing map指的是set内部使用的set map。了解更多信息。 http://www.jusfortechies.com/java/core-java/inside-set.php

于 2012-11-23T07:36:32.033 回答