001: /******************************************************************************
002: * ComparisonMap.java
003: *****************************************************************************/package org.openlaszlo.utils;
004:
005: import java.util.*;
006:
007: /**
008: * Hash table that stores keys case-sensitively, but compares them
009: * case-insensitively
010: *
011: * This differs from
012: * org.apache.commons.collections.map.CaseInsensitiveMap in that it
013: * preserves the first case used for a key (rather than converting all
014: * keys to lower case)
015: *
016: */
017: public class ComparisonMap extends LinkedHashMap {
018:
019: /** canonical lower-case map */
020: private HashMap keyMap;
021:
022: public Set normalizedKeySet() {
023: return keyMap.keySet();
024: }
025:
026: public ComparisonMap() {
027: super ();
028: keyMap = new HashMap();
029: }
030:
031: public ComparisonMap(int initialCapacity) {
032: super (initialCapacity);
033: keyMap = new HashMap(initialCapacity);
034: }
035:
036: public ComparisonMap(int initialCapacity, float loadFactor) {
037: super (initialCapacity, loadFactor);
038: keyMap = new HashMap(initialCapacity, loadFactor);
039: }
040:
041: public ComparisonMap(Map m) {
042: this (m.size());
043: putAll(m);
044: }
045:
046: private Object caseInsensitiveKey(Object key) {
047: return key instanceof String ? ((String) key).toLowerCase()
048: : key;
049: }
050:
051: public void clear() {
052: keyMap.clear();
053: super .clear();
054: }
055:
056: public Object clone() {
057: return new ComparisonMap(this );
058: }
059:
060: public boolean containsKey(Object key) {
061: return keyMap.containsKey(caseInsensitiveKey(key));
062: }
063:
064: public boolean containsKey(Object key, boolean caseSensitive) {
065: if (caseSensitive) {
066: return keyMap.containsKey(key);
067: } else {
068: return keyMap.containsKey(caseInsensitiveKey(key));
069: }
070: }
071:
072: /* containsValue just works */
073:
074: /* entrySet just works, keys have original case */
075:
076: public Object get(Object key) {
077: key = caseInsensitiveKey(key);
078: if (keyMap.containsKey(key)) {
079: return super .get(keyMap.get(key));
080: } else {
081: return null;
082: }
083: }
084:
085: /* isEmpty just works */
086:
087: /* keySet just works, keys have original case */
088:
089: public Object put(Object key, Object value) {
090: keyMap.put(caseInsensitiveKey(key), key);
091: return super .put(key, value);
092: }
093:
094: public void putAll(Map m) {
095: for (Iterator i = m.entrySet().iterator(); i.hasNext();) {
096: Map.Entry entry = (Map.Entry) i.next();
097: put(entry.getKey(), entry.getValue());
098: }
099: }
100:
101: public Object remove(Object key) {
102: key = caseInsensitiveKey(key);
103: if (keyMap.containsKey(key)) {
104: return super .remove(keyMap.remove(key));
105: } else {
106: return null;
107: }
108: }
109:
110: /* size just works */
111:
112: /* values just works */
113:
114: }
|