001 /*--------------------------------------------------------------------------+
002 $Id: IdManagerBase.java 26283 2010-02-18 11:18:57Z juergens $
003 | |
004 | Copyright 2005-2010 Technische Universitaet Muenchen |
005 | |
006 | Licensed under the Apache License, Version 2.0 (the "License"); |
007 | you may not use this file except in compliance with the License. |
008 | 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, software |
013 | distributed under the License is distributed on an "AS IS" BASIS, |
014 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
015 | See the License for the specific language governing permissions and |
016 | limitations under the License. |
017 +--------------------------------------------------------------------------*/
018 package edu.tum.cs.commons.collections;
019
020 import java.util.Map;
021
022 /**
023 * Base class for id managers.
024 *
025 *
026 * @author Florian Deissenboeck
027 * @author $Author: juergens $
028 * @version $Rev: 26283 $
029 * @levd.rating GREEN Hash: 90DF9C120C62D3E775BE3F45FBA0E008
030 */
031 public class IdManagerBase<K> {
032 /** Maps from object to ids. */
033 private final Map<K, Integer> ids;
034
035 /** the next id to bes used */
036 private int currentId = 0;
037
038 /**
039 * Create new id manager
040 *
041 * @param map
042 * maps from object to ids
043 */
044 protected IdManagerBase(Map<K, Integer> map) {
045 this.ids = map;
046 }
047
048 /**
049 * Obtain a unique id for an object. Note that obtaining a id for an object
050 * prevents it from being garbage collected.
051 */
052 public int obtainId(K k) {
053
054 // is already stored
055 if (ids.containsKey(k)) {
056 return ids.get(k);
057 }
058
059 ids.put(k, currentId);
060
061 // return id and increase it afterwards
062 return currentId++;
063 }
064
065 /**
066 * Clear the manager. Adding an object to the manager, clearing the manager
067 * and re-adding the object will not result in the same ids.
068 */
069 public void clear() {
070 ids.clear();
071 currentId = 0;
072 }
073 }