001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License.
018 *
019 */
020package org.apache.mina.util;
021
022import java.io.Serializable;
023import java.util.AbstractSet;
024import java.util.Collection;
025import java.util.Iterator;
026import java.util.Map;
027import java.util.Set;
028
029/**
030 * A {@link Map}-backed {@link Set}.
031 *
032 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
033 */
034public class MapBackedSet<E> extends AbstractSet<E> implements Serializable {
035
036    private static final long serialVersionUID = -8347878570391674042L;
037
038    protected final Map<E, Boolean> map;
039
040    public MapBackedSet(Map<E, Boolean> map) {
041        this.map = map;
042    }
043
044    public MapBackedSet(Map<E, Boolean> map, Collection<E> c) {
045        this.map = map;
046        addAll(c);
047    }
048
049    @Override
050    public int size() {
051        return map.size();
052    }
053
054    @Override
055    public boolean contains(Object o) {
056        return map.containsKey(o);
057    }
058
059    @Override
060    public Iterator<E> iterator() {
061        return map.keySet().iterator();
062    }
063
064    @Override
065    public boolean add(E o) {
066        return map.put(o, Boolean.TRUE) == null;
067    }
068
069    @Override
070    public boolean remove(Object o) {
071        return map.remove(o) != null;
072    }
073
074    @Override
075    public void clear() {
076        map.clear();
077    }
078}