PageRenderTime 26ms CodeModel.GetById 14ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/testability-explorer/src/main/java/com/google/test/metric/collection/LazyHashMap.java

http://testability-explorer.googlecode.com/
Java | 55 lines | 28 code | 8 blank | 19 comment | 2 complexity | 65f33cd8d56053fbcf78921e3f9f962d MD5 | raw file
 1/*
 2 * Copyright 2009 Google Inc.
 3 *
 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 5 * use this file except in compliance with the License. You may obtain a copy of
 6 * the License at
 7 *
 8 * http://www.apache.org/licenses/LICENSE-2.0
 9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16package com.google.test.metric.collection;
17
18import java.util.HashMap;
19import java.util.Map;
20
21import com.google.common.base.Supplier;
22import com.google.common.collect.ForwardingMap;
23
24/**
25 * Wrap a Map to provide lazy creation of its values.
26 * @author alexeagle@google.com (Alex Eagle)
27 */
28public class LazyHashMap<K, V> extends ForwardingMap<K,V> {
29  private final Map<K, V> delegate;
30  private final Supplier<V> supplier;
31
32  public LazyHashMap(Supplier<V> supplier) {
33    this.delegate = new HashMap<K,V>();
34    this.supplier = supplier;
35  }
36
37  protected Map<K, V> delegate() {
38    return delegate;
39  }
40
41  @Override
42  public V get(Object o) {
43    V value = delegate.get(o);
44    if (value == null) {
45      value = supplier.get();
46      delegate.put((K)o, value);
47    }
48    return value;
49  }
50
51  public static <K,V> Map<K, V> newLazyHashMap(Supplier<V> supplier) {
52    return new LazyHashMap<K,V>(supplier);
53  }
54
55}