001/*-------------------------------------------------------------------------+ 002| | 003| Copyright 2005-2011 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+-------------------------------------------------------------------------*/ 017package org.conqat.lib.commons.collections; 018 019import java.util.Map; 020 021/** 022 * Base class for id managers. 023 * 024 * 025 * @author Florian Deissenboeck 026 */ 027public class IdManagerBase<K> implements IIdProvider<Integer, K> { 028 /** Maps from object to ids. */ 029 private final Map<K, Integer> ids; 030 031 /** the next id to bes used */ 032 private int currentId = 0; 033 034 /** 035 * Create new id manager 036 * 037 * @param map 038 * maps from object to ids 039 */ 040 protected IdManagerBase(Map<K, Integer> map) { 041 this.ids = map; 042 } 043 044 /** 045 * Obtain a unique id for an object. Note that obtaining a id for an object 046 * prevents it from being garbage collected. 047 */ 048 @Override 049 public Integer obtainId(K k) { 050 051 // is already stored 052 if (ids.containsKey(k)) { 053 return ids.get(k); 054 } 055 056 ids.put(k, currentId); 057 058 // return id and increase it afterwards 059 return currentId++; 060 } 061 062 /** 063 * Clear the manager. Adding an object to the manager, clearing the manager 064 * and re-adding the object will not result in the same ids. 065 */ 066 public void clear() { 067 ids.clear(); 068 currentId = 0; 069 } 070}