1 package net.sf.morph.util;
2
3 import java.util.HashMap;
4 import java.util.Map;
5
6 import net.sf.composite.util.ObjectUtils;
7
8 /**
9 * @author Matt Sgarlata
10 * @since Jan 16, 2005
11 */
12 public class BidirectionalMap extends HashMap {
13
14 private final Map reverseMap;
15
16 public static BidirectionalMap getInstance(Map m) {
17 return m instanceof BidirectionalMap ? (BidirectionalMap) m : new BidirectionalMap(m);
18 }
19
20 public BidirectionalMap() {
21 super();
22 reverseMap = new HashMap();
23 }
24 public BidirectionalMap(int initialCapacity) {
25 super(initialCapacity);
26 reverseMap = new HashMap(initialCapacity);
27 }
28 public BidirectionalMap(int initialCapacity, float loadFactor) {
29 super(initialCapacity, loadFactor);
30 reverseMap = new HashMap(initialCapacity, loadFactor);
31 }
32 public BidirectionalMap(Map m) {
33 this(m.size());
34 putAll(m);
35 }
36
37 /**
38 * Retrieves the key that is registered for the given entry
39 */
40 public Object getKey(Object entry) {
41 return reverseMap.get(entry);
42 }
43
44 public void clear() {
45 super.clear();
46 reverseMap.clear();
47 }
48 public Object clone() {
49 HashMap clone = (HashMap) super.clone();
50 return new BidirectionalMap(clone);
51 }
52
53 public Object put(Object key, Object value) {
54 if (reverseMap.containsKey(value)) {
55 throw new IllegalArgumentException("The value '"
56 + ObjectUtils.getObjectDescription(value)
57 + "' has already been added to the map");
58 }
59 reverseMap.put(value, key);
60 return super.put(key, value);
61 }
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 public Object remove(Object key) {
80 Object value = get(key);
81 reverseMap.remove(value);
82 return super.remove(key);
83 }
84
85 public Map getReverseMap() {
86 return reverseMap;
87 }
88 }