001/* Copyright (C) 2013 TU Dortmund 002 * This file is part of AutomataLib, http://www.automatalib.net/. 003 * 004 * AutomataLib is free software; you can redistribute it and/or 005 * modify it under the terms of the GNU Lesser General Public 006 * License version 3.0 as published by the Free Software Foundation. 007 * 008 * AutomataLib is distributed in the hope that it will be useful, 009 * but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 011 * Lesser General Public License for more details. 012 * 013 * You should have received a copy of the GNU Lesser General Public 014 * License along with AutomataLib; if not, see 015 * http://www.gnu.de/documents/lgpl.en.html. 016 */ 017package net.automatalib.automata.base; 018 019import net.automatalib.automata.Automaton; 020import net.automatalib.commons.util.array.ResizingObjectArray; 021import net.automatalib.commons.util.mappings.MutableMapping; 022import net.automatalib.commons.util.nid.IDChangeListener; 023import net.automatalib.commons.util.nid.NumericID; 024 025public class StateIDDynamicMapping<S extends NumericID, V> implements MutableMapping<S, V>, 026 IDChangeListener<S> { 027 028 private final Automaton<S, ?, ?> automaton; 029 private final ResizingObjectArray storage; 030 031 public StateIDDynamicMapping(Automaton<S,?,?> automaton) { 032 this.automaton = automaton; 033 this.storage = new ResizingObjectArray(automaton.size()); 034 } 035 036 @Override 037 @SuppressWarnings("unchecked") 038 public V get(S elem) { 039 int id = elem.getId(); 040 if(id < storage.array.length) 041 return (V)storage.array[id]; 042 return null; 043 } 044 045 @Override 046 public void idChanged(S obj, int newId, int oldId) { 047 Object oldValue = null; 048 if(oldId > 0 && oldId < storage.array.length) { 049 oldValue = storage.array[oldId]; 050 storage.array[oldId] = null; 051 } 052 if(newId >= storage.array.length) 053 storage.ensureCapacity(automaton.size()); 054 storage.array[newId] = oldValue; 055 } 056 057 @Override 058 @SuppressWarnings("unchecked") 059 public V put(S key, V value) { 060 int id = key.getId(); 061 if(id >= storage.array.length) 062 storage.ensureCapacity(automaton.size()); 063 V old = (V)storage.array[id]; 064 storage.array[id] = value; 065 return old; 066 } 067 068}