1 /* 2 * Licensed to the Apache Software Foundation (ASF) under one 3 * or more contributor license agreements. See the NOTICE file 4 * distributed with this work for additional information 5 * regarding copyright ownership. The ASF licenses this file 6 * to you under the Apache License, Version 2.0 (the 7 * "License"); you may not use this file except in compliance 8 * with the License. You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, 13 * software distributed under the License is distributed on an 14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 * KIND, either express or implied. See the License for the 16 * specific language governing permissions and limitations 17 * under the License. 18 * 19 */ 20 package org.apache.mina.util; 21 22 import java.io.Serializable; 23 import java.util.AbstractSet; 24 import java.util.Collection; 25 import java.util.Iterator; 26 import java.util.Map; 27 import java.util.Set; 28 29 /** 30 * A {@link Map}-backed {@link Set}. 31 * 32 * @param <E> The element stored in the set 33 * 34 * @author <a href="http://mina.apache.org">Apache MINA Project</a> 35 */ 36 public class MapBackedSet<E> extends AbstractSet<E> implements Serializable { 37 38 private static final long serialVersionUID = -8347878570391674042L; 39 40 protected final Map<E, Boolean> map; 41 42 /** 43 * Creates a new MapBackedSet instance 44 * 45 * @param map The map that we want to back 46 */ 47 public MapBackedSet(Map<E, Boolean> map) { 48 this.map = map; 49 } 50 51 /** 52 * Creates a new MapBackedSet instance 53 * 54 * @param map The map that we want to back 55 * @param c The elements we want to add in the map 56 */ 57 public MapBackedSet(Map<E, Boolean> map, Collection<E> c) { 58 this.map = map; 59 addAll(c); 60 } 61 62 /** 63 * {@inheritDoc} 64 */ 65 @Override 66 public int size() { 67 return map.size(); 68 } 69 70 /** 71 * {@inheritDoc} 72 */ 73 @Override 74 public boolean contains(Object o) { 75 return map.containsKey(o); 76 } 77 78 /** 79 * {@inheritDoc} 80 */ 81 @Override 82 public Iterator<E> iterator() { 83 return map.keySet().iterator(); 84 } 85 86 /** 87 * {@inheritDoc} 88 */ 89 @Override 90 public boolean add(E o) { 91 return map.put(o, Boolean.TRUE) == null; 92 } 93 94 /** 95 * {@inheritDoc} 96 */ 97 @Override 98 public boolean remove(Object o) { 99 return map.remove(o) != null; 100 } 101 102 /** 103 * {@inheritDoc} 104 */ 105 @Override 106 public void clear() { 107 map.clear(); 108 } 109 }