All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gw.util.ScopedMap Maven / Gradle / Ivy

There is a newer version: 1.18.2
Show newest version
/*
 * Copyright 2014 Guidewire Software, Inc.
 */

package gw.util;

import java.util.*;

public class ScopedMap extends AbstractMap {

  private final ScopedMap _parent;
  private Map _overlayMap = Collections.emptyMap();

  public ScopedMap() {
    _parent = null;
  }

  private ScopedMap(ScopedMap parent) {
    _parent = parent;
  }

  public int size() {
    return getEntryMap().size();
  }

  public boolean isEmpty() {
    return getEntryMap().isEmpty();
  }

  public boolean containsKey(Object key) {
    return get(key) != null;
  }

  public boolean containsValue(Object value) {
    return getEntryMap().containsValue( value );
  }

  public V get(Object key) {
    V value = _overlayMap.get(key);
    if (value != null) {
      return value;
    }
    //noinspection SuspiciousMethodCalls
    if (_overlayMap.containsKey(key)) {
      return null;
    }
    return _parent == null ? null : _parent.get(key);
  }

  public V put(K key, V value) {
    initOverlayMap();
    V oldValue = get(key);
    _overlayMap.put(key, value);
    return oldValue;
  }

  public V remove(Object key) {
    initOverlayMap();
    V oldValue = get(key);
    //noinspection unchecked
    _overlayMap.put((K) key, null);
    return oldValue;
  }

  public void putAll(Map t) {
    for (Entry entry : t.entrySet()) {
      put(entry.getKey(), entry.getValue());
    }
  }

  public ScopedMap pushScope() {
    if( !_overlayMap.isEmpty() ) {
      ((SpaceEfficientHashMap)_overlayMap).trimToSize();
    }
    return new ScopedMap(this);
  }

  public ScopedMap popScope() {
    return _parent;
  }

  public void clear() {
    throw new UnsupportedOperationException();
  }

  public Set keySet() {
    return getEntryMap().keySet();
  }

  public Collection values() {
    return getEntryMap().values();
  }

  public Set> entrySet() {
    return getEntryMap().entrySet();
  }

  private Map getEntryMap() {
    Map results = new HashMap();
    getEntryMap( results );
    return results;
  }

  private void getEntryMap( Map results ) {
    if ( _parent != null ) {
      _parent.getEntryMap( results );
    }
    initOverlayMap();
    results.putAll( _overlayMap );
  }

  public boolean containsKeyDirect( K key ) {
    return _overlayMap.containsKey( key );
  }

  public V getDirect( K key ) {
    return _overlayMap.get( key );
  }

  private void initOverlayMap() {
    if( _overlayMap == Collections.emptyMap() ) {
      _overlayMap = new SpaceEfficientHashMap();
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy