1 22 23 28 29 package org.xquark.mapper.util; 30 31 import java.util.*; 32 33 37 public class CounterMap extends HashMap 38 { 39 private static final String RCSRevision = "$Revision: 1.1 $"; 40 private static final String RCSName = "$Name: $"; 41 42 public boolean containsValue(Object value) 43 { 44 return super.containsValue(new ValueInfo(value)); 45 } 46 47 public Object get(Object key) 48 { 49 ValueInfo value = (ValueInfo)super.get(key); 50 if (value == null) 51 return null; 52 else 53 return value.get(); 54 } 55 56 public Object checkOut(Object key) 57 { 58 ValueInfo info = (ValueInfo)super.get(key); 59 60 if (info == null) 61 return null; 62 else 63 info.inc(); 64 65 return info.get(); 66 } 67 68 71 public Object put(Object key, Object value) 72 { 73 Object info = checkOut(key); 74 75 if (info == null) 76 { 77 super.put(key, new ValueInfo(value)); 78 return null; 79 } 80 81 return info; 82 } 83 84 public void putAll(Map t) { throw new UnsupportedOperationException ();} 85 86 89 public Object remove(Object key) 90 { 91 ValueInfo info = (ValueInfo)super.get(key); 92 93 if (info == null) 94 return null; 95 else 96 info.dec(); 97 98 if (info.isUsed()) 99 return null; 100 else 101 super.remove(key); 102 103 return info.get(); 104 } 105 106 108 public Object removeAll(Object key) 109 { 110 ValueInfo info = (ValueInfo)super.remove(key); 111 if (info == null) 112 return null; 113 else 114 return info.get(); 115 } 116 117 public Set entrySet() 118 { 119 Map.Entry wEntry; 120 HashSet res = new HashSet(); 121 Iterator it = super.entrySet().iterator(); 122 while (it.hasNext()) 123 { 124 wEntry = (Map.Entry)it.next(); 125 res.add(((ValueInfo)wEntry.getValue()).get()); 126 } 127 return res; 128 } 129 130 public Collection values() 131 { 132 ArrayList list = new ArrayList(); 133 Iterator it = super.values().iterator(); 134 while (it.hasNext()) 135 { 136 list.add(((ValueInfo)it.next()).get()); 137 } 138 return list; 139 } 140 141 142 public void setKey(Object oldKey, Object newKey) 143 { 144 if (containsKey(oldKey)) 145 super.put(newKey, super.remove(oldKey)); 146 } 147 148 155 public class ValueInfo 156 { 157 private Object o; 158 private int use = 1; 159 160 ValueInfo(Object o) { this.o = o;} 161 162 void inc() { use++;} 163 void dec() { use--;} 164 public boolean isNotUsed() { return (use < 1); } 165 public boolean isUsed() { return (use > 0); } 166 public Object get() { return o;} 167 public boolean equals(Object o) {return o.equals(this.o);} 168 } 169 } 170 | Popular Tags |