001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  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.apache.commons.collections4.map;
018
019import java.io.IOException;
020import java.io.ObjectInputStream;
021import java.io.ObjectOutputStream;
022import java.io.Serializable;
023import java.util.Collection;
024import java.util.Map;
025import java.util.Set;
026
027import org.apache.commons.collections4.BoundedMap;
028import org.apache.commons.collections4.collection.UnmodifiableCollection;
029import org.apache.commons.collections4.set.UnmodifiableSet;
030
031/**
032 * Decorates another <code>Map</code> to fix the size, preventing add/remove.
033 * <p>
034 * Any action that would change the size of the map is disallowed.
035 * The put method is allowed to change the value associated with an existing
036 * key however.
037 * <p>
038 * If trying to remove or clear the map, an UnsupportedOperationException is
039 * thrown. If trying to put a new mapping into the map, an
040 * IllegalArgumentException is thrown. This is because the put method can
041 * succeed if the mapping's key already exists in the map, so the put method
042 * is not always unsupported.
043 * <p>
044 * <strong>Note that FixedSizeMap is not synchronized and is not thread-safe.</strong>
045 * If you wish to use this map from multiple threads concurrently, you must use
046 * appropriate synchronization. The simplest approach is to wrap this map
047 * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
048 * exceptions when accessed by concurrent threads without synchronization.
049 * <p>
050 * This class is Serializable from Commons Collections 3.1.
051 *
052 * @param <K> the type of the keys in this map
053 * @param <V> the type of the values in this map
054 * @since 3.0
055 */
056public class FixedSizeMap<K, V>
057        extends AbstractMapDecorator<K, V>
058        implements BoundedMap<K, V>, Serializable {
059
060    /** Serialization version */
061    private static final long serialVersionUID = 7450927208116179316L;
062
063    /**
064     * Factory method to create a fixed size map.
065     *
066     * @param <K>  the key type
067     * @param <V>  the value type
068     * @param map  the map to decorate, must not be null
069     * @return a new fixed size map
070     * @throws NullPointerException if map is null
071     * @since 4.0
072     */
073    public static <K, V> FixedSizeMap<K, V> fixedSizeMap(final Map<K, V> map) {
074        return new FixedSizeMap<>(map);
075    }
076
077    //-----------------------------------------------------------------------
078    /**
079     * Constructor that wraps (not copies).
080     *
081     * @param map  the map to decorate, must not be null
082     * @throws NullPointerException if map is null
083     */
084    protected FixedSizeMap(final Map<K, V> map) {
085        super(map);
086    }
087
088    //-----------------------------------------------------------------------
089    /**
090     * Write the map out using a custom routine.
091     *
092     * @param out  the output stream
093     * @throws IOException if an error occurs while writing to the stream
094     * @since 3.1
095     */
096    private void writeObject(final ObjectOutputStream out) throws IOException {
097        out.defaultWriteObject();
098        out.writeObject(map);
099    }
100
101    /**
102     * Read the map in using a custom routine.
103     *
104     * @param in  the input stream
105     * @throws IOException if an error occurs while reading from the stream
106     * @throws ClassNotFoundException if an object read from the stream can not be loaded
107     * @since 3.1
108     */
109    @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
110    private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
111        in.defaultReadObject();
112        map = (Map<K, V>) in.readObject(); // (1)
113    }
114
115    //-----------------------------------------------------------------------
116    @Override
117    public V put(final K key, final V value) {
118        if (map.containsKey(key) == false) {
119            throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
120        }
121        return map.put(key, value);
122    }
123
124    @Override
125    public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
126        for (final K key : mapToCopy.keySet()) {
127            if (!containsKey(key)) {
128                throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
129            }
130        }
131        map.putAll(mapToCopy);
132    }
133
134    @Override
135    public void clear() {
136        throw new UnsupportedOperationException("Map is fixed size");
137    }
138
139    @Override
140    public V remove(final Object key) {
141        throw new UnsupportedOperationException("Map is fixed size");
142    }
143
144    @Override
145    public Set<Map.Entry<K, V>> entrySet() {
146        final Set<Map.Entry<K, V>> set = map.entrySet();
147        // unmodifiable set will still allow modification via Map.Entry objects
148        return UnmodifiableSet.unmodifiableSet(set);
149    }
150
151    @Override
152    public Set<K> keySet() {
153        final Set<K> set = map.keySet();
154        return UnmodifiableSet.unmodifiableSet(set);
155    }
156
157    @Override
158    public Collection<V> values() {
159        final Collection<V> coll = map.values();
160        return UnmodifiableCollection.unmodifiableCollection(coll);
161    }
162
163    @Override
164    public boolean isFull() {
165        return true;
166    }
167
168    @Override
169    public int maxSize() {
170        return size();
171    }
172
173}