ChainedDictionary.java
/***************************************************************************
Copyright 2012 Emily Estes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
***************************************************************************/
package net.metanotion.util;
import java.util.Map;
/** Create a two tiered dictionary that chains failed key lookups to a parent dictionary.
@param <K> The type of keys this dictionary uses as an index.
@param <V> The type of values this dictionary stores.
*/
public final class ChainedDictionary<K,V> implements Dictionary<K,V> {
private final Dictionary<K,V> self;
private final Dictionary<K,V> parent;
/** Create a new dictionary backed by a primary and parent dictionary. In this case
the two dictionary's are maps that will be wrapped by the MapDictionaryAdapter.
@param self The first dictionary to look up values in
@param parent The secondary dictionary. If the value can't be found in the first
dictionary(<code>self.get(k) == null</code>), this one is attempted next. */
public ChainedDictionary(Map<K,V> self, Map<K,V> parent) {
this(new MapDictionaryAdapter<K,V>(self), new MapDictionaryAdapter<K,V>(parent));
}
/** Create a new dictionary backed by a primary and parent dictionary. In this case
the first dictionary's is a map that will be wrapped by the MapDictionaryAdapter.
@param self The first dictionary to look up values in
@param parent The secondary dictionary. If the value can't be found in the first
dictionary(<code>self.get(k) == null</code>), this one is attempted next. */
public ChainedDictionary(Map<K,V> self, Dictionary<K,V> parent) {
this(new MapDictionaryAdapter<K,V>(self), parent);
}
/** Create a new dictionary backed by a primary and parent dictionary.
@param self The first dictionary to look up values in
@param parent The secondary dictionary. If the value can't be found in the first
dictionary(<code>self.get(k) == null</code>), this one is attempted next. */
public ChainedDictionary(Dictionary<K,V> self, Dictionary<K,V> parent) {
this.self = self;
this.parent = parent;
}
@Override public V get(K key) {
final V result = self.get(key);
if(result != null) { return result; }
return parent.get(key);
}
}