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.commons.util.mappings; 018 019import net.automatalib.commons.util.array.ResizingObjectArray; 020import net.automatalib.commons.util.nid.IDChangeListener; 021import net.automatalib.commons.util.nid.NumericID; 022 023public final class ArrayMapping<K extends NumericID, V> implements MutableMapping<K, V>, 024 IDChangeListener<K> { 025 026 private final ResizingObjectArray storage; 027 028 public ArrayMapping() { 029 storage = new ResizingObjectArray(); 030 } 031 032 public ArrayMapping(int initialSize) { 033 storage = new ResizingObjectArray(initialSize); 034 } 035 036 @Override 037 @SuppressWarnings("unchecked") 038 public V get(K elem) { 039 int id = elem.getId(); 040 if(id >= storage.array.length) 041 return null; 042 return (V)storage.array[id]; 043 } 044 045 @Override 046 @SuppressWarnings("unchecked") 047 public V put(K key, V value) { 048 int id = key.getId(); 049 storage.ensureCapacity(id+1); 050 V old = (V)storage.array[id]; 051 storage.array[id] = value; 052 return old; 053 } 054 055 @Override 056 public void idChanged(K obj, int newId, int oldId) { 057 if(newId == -1) { 058 if(oldId < storage.array.length) 059 storage.array[oldId] = null; 060 return; 061 } 062 Object oldVal = null; 063 if(oldId < storage.array.length) { 064 oldVal = storage.array[oldId]; 065 storage.array[oldId] = oldVal; 066 } 067 storage.ensureCapacity(newId+1); 068 storage.array[newId] = oldVal; 069 } 070 071}