如何制作一张由地图支持的套装?

Heg*_*ggi 6 java collections map set

Collections类中有一个方法.

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

支持地图地图支持的集合意味着什么?

Chr*_*tin 7

看看实施可能会很有启发性:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 - 添加说明:

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

e向集合中添加元素时,会e -> true向地图添加一个条目.

public boolean add(E e) { return m.put(e, Boolean.TRUE) == null; }
Run Code Online (Sandbox Code Playgroud)

因此,这个类将您Map转变为一个对象,其行为类似于Set简单地忽略事物映射到的值,并且仅使用键.


sun*_*nil 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);
Run Code Online (Sandbox Code Playgroud)

和输出

[]
{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]
Run Code Online (Sandbox Code Playgroud)