View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.collections4.map;
18  
19  import java.io.IOException;
20  import java.io.ObjectInputStream;
21  import java.io.ObjectOutputStream;
22  import java.io.Serializable;
23  import java.util.Collection;
24  import java.util.Map;
25  import java.util.Set;
26  
27  import org.apache.commons.collections4.BoundedMap;
28  import org.apache.commons.collections4.collection.UnmodifiableCollection;
29  import org.apache.commons.collections4.set.UnmodifiableSet;
30  
31  /**
32   * Decorates another {@code Map} to fix the size, preventing add/remove.
33   * <p>
34   * Any action that would change the size of the map is disallowed.
35   * The put method is allowed to change the value associated with an existing
36   * key however.
37   * </p>
38   * <p>
39   * If trying to remove or clear the map, an UnsupportedOperationException is
40   * thrown. If trying to put a new mapping into the map, an
41   * IllegalArgumentException is thrown. This is because the put method can
42   * succeed if the mapping's key already exists in the map, so the put method
43   * is not always unsupported.
44   * </p>
45   * <p>
46   * <strong>Note that FixedSizeMap is not synchronized and is not thread-safe.</strong>
47   * If you wish to use this map from multiple threads concurrently, you must use
48   * appropriate synchronization. The simplest approach is to wrap this map
49   * using {@link java.util.Collections#synchronizedMap(Map)}. This class may throw
50   * exceptions when accessed by concurrent threads without synchronization.
51   * </p>
52   * <p>
53   * This class is Serializable from Commons Collections 3.1.
54   * </p>
55   *
56   * @param <K> The type of the keys in this map
57   * @param <V> The type of the values in this map
58   * @since 3.0
59   */
60  public class FixedSizeMap<K, V>
61          extends AbstractMapDecorator<K, V>
62          implements BoundedMap<K, V>, Serializable {
63  
64      /** Serialization version */
65      private static final long serialVersionUID = 7450927208116179316L;
66  
67      /**
68       * Factory method to create a fixed size map.
69       *
70       * @param <K>  the key type
71       * @param <V>  the value type
72       * @param map  The map to decorate, must not be null
73       * @return A new fixed size map
74       * @throws NullPointerException if map is null
75       * @since 4.0
76       */
77      public static <K, V> FixedSizeMap<K, V> fixedSizeMap(final Map<K, V> map) {
78          return new FixedSizeMap<>(map);
79      }
80  
81      /**
82       * Constructor that wraps (not copies).
83       *
84       * @param map  The map to decorate, must not be null
85       * @throws NullPointerException if map is null
86       */
87      protected FixedSizeMap(final Map<K, V> map) {
88          super(map);
89      }
90  
91      /**
92       * Always throws {@link UnsupportedOperationException}.
93       *
94       * @throws UnsupportedOperationException Always thrown.
95       */
96      @Override
97      public void clear() {
98          throw new UnsupportedOperationException("Map is fixed size");
99      }
100 
101     @Override
102     public Set<Map.Entry<K, V>> entrySet() {
103         final Set<Map.Entry<K, V>> set = map.entrySet();
104         // unmodifiable set will still allow modification via Map.Entry objects
105         return UnmodifiableSet.unmodifiableSet(set);
106     }
107 
108     @Override
109     public boolean isFull() {
110         return true;
111     }
112 
113     @Override
114     public Set<K> keySet() {
115         final Set<K> set = map.keySet();
116         return UnmodifiableSet.unmodifiableSet(set);
117     }
118 
119     @Override
120     public int maxSize() {
121         return size();
122     }
123 
124     @Override
125     public V put(final K key, final V value) {
126         if (!map.containsKey(key)) {
127             throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
128         }
129         return map.put(key, value);
130     }
131 
132     @Override
133     public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
134         for (final K key : mapToCopy.keySet()) {
135             if (!containsKey(key)) {
136                 throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
137             }
138         }
139         map.putAll(mapToCopy);
140     }
141 
142     /**
143      * Deserializes the map in using a custom routine.
144      *
145      * @param in  The input stream
146      * @throws IOException Thrown if an error occurs while reading from the stream
147      * @throws ClassNotFoundException if an object read from the stream cannot be loaded
148      * @since 3.1
149      */
150     @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
151     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
152         in.defaultReadObject();
153         map = (Map<K, V>) in.readObject(); // (1)
154     }
155 
156     /**
157      * Always throws {@link UnsupportedOperationException}.
158      *
159      * @param key Ignored.
160      * @throws UnsupportedOperationException Always thrown.
161      */
162     @Override
163     public V remove(final Object key) {
164         throw new UnsupportedOperationException("Map is fixed size");
165     }
166 
167     @Override
168     public Collection<V> values() {
169         return UnmodifiableCollection.unmodifiableCollection(map.values());
170     }
171 
172     /**
173      * Serializes this object to an ObjectOutputStream.
174      *
175      * @param out The target ObjectOutputStream.
176      * @throws IOException thrown when an I/O errors occur writing to the target stream.
177      * @since 3.1
178      */
179     private void writeObject(final ObjectOutputStream out) throws IOException {
180         out.defaultWriteObject();
181         out.writeObject(map);
182     }
183 
184 }