package textbender.g.util; // Copyright 2006, Michael Allan. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Textbender Software"), to deal in the Textbender Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicence, and/or sell copies of the Textbender Software, and to permit persons to whom the Textbender Software is furnished to do so, subject to the following conditions: The preceding copyright notice and this permission notice shall be included in all copies or substantial portions of the Textbender Software. THE TEXTBENDER SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE TEXTBENDER SOFTWARE OR THE USE OR OTHER DEALINGS IN THE TEXTBENDER SOFTWARE. import java.util.HashMap; import textbender.g.lang.ThreadRestricted; /** A multi-map optimized for the case of rare multiples. * For each extra value put to a key (beyond one), * a larger array is created to accommodate it. */ public @ThreadRestricted("per java.util.HashMap") final class MultiMapRM implements MultiMap { /** Constructs a MultiMapRM, with default initial capacity etc. per java.util.HashMap. */ public MultiMapRM() { hashMap = new HashMap(); } // - M u l t i - M a p ---------------------------------------------------------------- public Object get( Object key ) { return hashMap.get( key ); } /** @throws NullPointerException if value is null */ public void put( final K key, final V value ) { if( value == null ) throw new NullPointerException(); // null reserved for detection, below final Object oldValue = hashMap.put( key, value ); if( oldValue == null ) return; final Object[] newArray; if( oldValue instanceof Object[] ) { Object[] oldArray = (Object[])oldValue; newArray = new Object[oldArray.length + 1]; for( int v = 0;; ++v ) { if( v < oldArray.length ) newArray[v] = oldArray[v]; else { newArray[v] = value; break; } } } else newArray = new Object[]{ oldValue, value }; hashMap.put( key, newArray ); } //// P r i v a t e /////////////////////////////////////////////////////////////////////// /** The underlying map, on which this multi-map is built. * Values are either Object[] or Object. */ private final HashMap hashMap; }