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    *      http://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      @Override
92      public void clear() {
93          throw new UnsupportedOperationException("Map is fixed size");
94      }
95  
96      @Override
97      public Set<Map.Entry<K, V>> entrySet() {
98          final Set<Map.Entry<K, V>> set = map.entrySet();
99          // unmodifiable set will still allow modification via Map.Entry objects
100         return UnmodifiableSet.unmodifiableSet(set);
101     }
102 
103     @Override
104     public boolean isFull() {
105         return true;
106     }
107 
108     @Override
109     public Set<K> keySet() {
110         final Set<K> set = map.keySet();
111         return UnmodifiableSet.unmodifiableSet(set);
112     }
113 
114     @Override
115     public int maxSize() {
116         return size();
117     }
118 
119     @Override
120     public V put(final K key, final V value) {
121         if (!map.containsKey(key)) {
122             throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
123         }
124         return map.put(key, value);
125     }
126 
127     @Override
128     public void putAll(final Map<? extends K, ? extends V> mapToCopy) {
129         for (final K key : mapToCopy.keySet()) {
130             if (!containsKey(key)) {
131                 throw new IllegalArgumentException("Cannot put new key/value pair - Map is fixed size");
132             }
133         }
134         map.putAll(mapToCopy);
135     }
136 
137     /**
138      * Read the map in using a custom routine.
139      *
140      * @param in  the input stream
141      * @throws IOException if an error occurs while reading from the stream
142      * @throws ClassNotFoundException if an object read from the stream can not be loaded
143      * @since 3.1
144      */
145     @SuppressWarnings("unchecked") // (1) should only fail if input stream is incorrect
146     private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
147         in.defaultReadObject();
148         map = (Map<K, V>) in.readObject(); // (1)
149     }
150 
151     @Override
152     public V remove(final Object key) {
153         throw new UnsupportedOperationException("Map is fixed size");
154     }
155 
156     @Override
157     public Collection<V> values() {
158         final Collection<V> coll = map.values();
159         return UnmodifiableCollection.unmodifiableCollection(coll);
160     }
161 
162     /**
163      * Write the map out using a custom routine.
164      *
165      * @param out  the output stream
166      * @throws IOException if an error occurs while writing to the stream
167      * @since 3.1
168      */
169     private void writeObject(final ObjectOutputStream out) throws IOException {
170         out.defaultWriteObject();
171         out.writeObject(map);
172     }
173 
174 }