1 package com.thaiopensource.util; 2 3 import java.util.Hashtable ; 4 import java.util.Enumeration ; 5 6 public class PropertyMapBuilder { 7 private Hashtable map; 8 private PropertyId[] keys; 9 10 private static class PropertyMapImpl implements PropertyMap { 11 private final Hashtable map; 12 private final PropertyId[] keys; 13 14 private PropertyMapImpl(Hashtable map, PropertyId[] keys) { 15 this.map = map; 16 this.keys = keys; 17 } 18 19 public Object get(PropertyId pid) { 20 return map.get(pid); 21 } 22 23 public int size() { 24 return keys.length; 25 } 26 27 public boolean contains(PropertyId pid) { 28 return map.get(pid) != null; 29 } 30 31 public PropertyId getKey(int i) { 32 return keys[i]; 33 } 34 } 35 36 public PropertyMapBuilder() { 37 this.map = new Hashtable (); 38 } 39 40 public PropertyMapBuilder(PropertyMap pm) { 41 if (pm instanceof PropertyMapImpl) { 42 PropertyMapImpl pmi = (PropertyMapImpl)pm; 43 this.map = pmi.map; 44 this.keys = pmi.keys; 45 } 46 else { 47 this.map = new Hashtable (); 48 for (int i = 0, len = pm.size(); i < len; i++) { 49 PropertyId pid = pm.getKey(i); 50 put(pid, pm.get(pid)); 51 } 52 } 53 } 54 55 private void lock() { 56 if (keys != null) 57 return; 58 keys = new PropertyId[map.size()]; 59 int i = 0; 60 for (Enumeration e = map.keys(); e.hasMoreElements();) 61 keys[i++] = (PropertyId)e.nextElement(); 62 } 63 64 private void copyIfLocked() { 65 if (keys == null) 66 return; 67 Hashtable newMap = new Hashtable (); 68 for (int i = 0; i < keys.length; i++) 69 newMap.put(keys[i], map.get(keys[i])); 70 map = newMap; 71 keys = null; 72 } 73 74 public PropertyMap toPropertyMap() { 75 lock(); 76 return new PropertyMapImpl(map, keys); 77 } 78 79 public Object put(PropertyId id, Object value) { 80 copyIfLocked(); 81 if (value == null) 82 return map.remove(id); 83 if (!id.getValueClass().isInstance(value)) 84 throw new ClassCastException (); 85 return map.put(id, value); 86 } 87 88 public Object get(PropertyId pid) { 89 return map.get(pid); 90 } 91 92 public boolean contains(PropertyId pid) { 93 return map.get(pid) != null; 94 } 95 } 96 | Popular Tags |