001/*-------------------------------------------------------------------------+ 002| | 003| Copyright (c) 2005-2019 The ConQAT Project | 004| | 005| Licensed under the Apache License, Version 2.0 (the "License"); | 006| you may not use this file except in compliance with the License. | 007| You may obtain a copy of the License at | 008| | 009| http://www.apache.org/licenses/LICENSE-2.0 | 010| | 011| Unless required by applicable law or agreed to in writing, software | 012| distributed under the License is distributed on an "AS IS" BASIS, | 013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | 014| See the License for the specific language governing permissions and | 015| limitations under the License. | 016| | 017+-------------------------------------------------------------------------*/ 018package org.conqat.lib.commons.collections; 019 020import java.util.AbstractSet; 021import java.util.Iterator; 022import java.util.Map; 023 024/** Base class for set implementations based on a backing set. */ 025public abstract class MapBackedSetBase<E> extends AbstractSet<E> { 026 027 /** Dummy object for the map. */ 028 private static final Object PRESENT = new Object(); 029 030 /** The map that actually stores the values. */ 031 private final Map<E, Object> map; 032 033 protected MapBackedSetBase(Map<E, Object> map) { 034 this.map = map; 035 } 036 037 @Override 038 public boolean add(E o) { 039 return map.put(o, PRESENT) == null; 040 } 041 042 @Override 043 public void clear() { 044 map.clear(); 045 } 046 047 @Override 048 public boolean contains(Object o) { 049 return map.containsKey(o); 050 } 051 052 @Override 053 public boolean isEmpty() { 054 return map.isEmpty(); 055 } 056 057 @Override 058 public Iterator<E> iterator() { 059 return map.keySet().iterator(); 060 } 061 062 @Override 063 public boolean remove(Object o) { 064 return map.remove(o) == PRESENT; 065 } 066 067 @Override 068 public int size() { 069 return map.size(); 070 } 071}