1/*
2 * Copyright (C) 2011 The Guava Authors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of 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,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.google.common.collect;
18
19import com.google.common.annotations.GwtCompatible;
20
21import java.util.Map;
22import java.util.Set;
23
24/**
25 * Workaround for
26 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6312706">
27 * EnumMap bug</a>. If you want to pass an {@code EnumMap}, with the
28 * intention of using its {@code entrySet()} method, you should
29 * wrap the {@code EnumMap} in this class instead.
30 *
31 * @author Dimitris Andreou
32 */
33@GwtCompatible
34final class WellBehavedMap<K, V> extends ForwardingMap<K, V> {
35  private final Map<K, V> delegate;
36  private Set<Entry<K, V>> entrySet;
37
38  private WellBehavedMap(Map<K, V> delegate) {
39    this.delegate = delegate;
40  }
41
42  /**
43   * Wraps the given map into a {@code WellBehavedEntriesMap}, which
44   * intercepts its {@code entrySet()} method by taking the
45   * {@code Set<K> keySet()} and transforming it to
46   * {@code Set<Entry<K, V>>}. All other invocations are delegated as-is.
47   */
48  static <K, V> WellBehavedMap<K, V> wrap(Map<K, V> delegate) {
49    return new WellBehavedMap<K, V>(delegate);
50  }
51
52  @Override protected Map<K, V> delegate() {
53    return delegate;
54  }
55
56  @Override public Set<Entry<K, V>> entrySet() {
57    Set<Entry<K, V>> es = entrySet;
58    if (es != null) {
59      return es;
60    }
61    return entrySet = Sets.transform(
62        delegate.keySet(), new KeyToEntryConverter<K, V>(this));
63  }
64
65  private static class KeyToEntryConverter<K, V>
66      extends Sets.InvertibleFunction<K, Map.Entry<K, V>> {
67    final Map<K, V> map;
68
69    KeyToEntryConverter(Map<K, V> map) {
70      this.map = map;
71    }
72
73    @Override public Map.Entry<K, V> apply(final K key) {
74      return new AbstractMapEntry<K, V>() {
75        @Override public K getKey() {
76          return key;
77        }
78        @Override public V getValue() {
79          return map.get(key);
80        }
81        @Override public V setValue(V value) {
82          return map.put(key, value);
83        }
84      };
85    }
86
87    @Override public K invert(Map.Entry<K, V> entry) {
88      return entry.getKey();
89    }
90  }
91}
92