View Javadoc

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  //	public void putAll(Map m) {
63  //		super.putAll(m);
64  //		if (m != null) {
65  //			Iterator keys = m.keySet().iterator();
66  //			while (keys != null && keys.hasNext()) {
67  //				Object key = keys.next();
68  //				Object value = m.get(key);
69  //				if (reverseMap.containsKey(value)) {
70  //					throw new IllegalArgumentException("Duplicate value "
71  //						+ ObjectUtils.getObjectDescription(value)
72  //						+ " found in map "
73  //						+ ObjectUtils.getObjectDescription(m));
74  //				}
75  //				reverseMap.put(value, key);
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  }