BUG-4158: introduce ImmutableOffsetMap
[yangtools.git] / common / util / src / main / java / org / opendaylight / yangtools / util / AbstractLazyValueMap.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.util;
9
10 import com.google.common.annotations.Beta;
11 import java.util.AbstractMap;
12
13 /**
14  * Abstract base class for maps which support lazy value object instantiation. This is useful in situations where a
15  * subset of values stored in the map are simple wrappers around some value. Using this abstraction can make the
16  * memory/CPU tradeoff by storing the bare minimum to re-create the value object, thus saving memory.
17  *
18  * @param <K> the type of keys maintained by this map
19  * @param <V> the type of mapped values
20  */
21 @Beta
22 public abstract class AbstractLazyValueMap<K, V> extends AbstractMap<K, V> {
23     /**
24      * Derive the value stored for a key/object pair. Subclasses can override this method and {@link #valueToObject(Object)}
25      * to improve memory efficiency.
26      *
27      * @param key Key being looked up
28      * @param obj Internally-stored object for the key
29      * @return Value to be returned to the user.
30      */
31     @SuppressWarnings("unchecked")
32     protected V objectToValue(final K key, final Object obj) {
33         return (V)obj;
34     }
35
36     /**
37      * Derive the object to be stored in the backing array. Subclasses can override this method and {@link #objectToValue(Object, Object)}
38      * to instantiate value objects as they are looked up without storing them in the map.
39      *
40      * @param value Value being looked up
41      * @return Stored object which corresponds to the value.
42      */
43     protected Object valueToObject(final V value) {
44         return value;
45     }
46 }