1 9 package org.jboss.portal.common.util; 10 11 import java.util.Collections ; 12 import java.util.HashMap ; 13 import java.util.HashSet ; 14 import java.util.Iterator ; 15 import java.util.Map ; 16 import java.util.Set ; 17 import java.io.Serializable ; 18 19 26 public class SetMap implements Serializable 27 { 28 29 30 static final long serialVersionUID = -7239767000556095977L; 31 32 33 private Map map; 34 35 public SetMap() 36 { 37 map = new HashMap (); 38 } 39 40 45 public SetMap(SetMap other) throws IllegalArgumentException 46 { 47 if (other == null) 48 { 49 throw new IllegalArgumentException ("Cannot copy null argument"); 50 } 51 map = new HashMap (); 52 for (Iterator i = other.map.entrySet().iterator(); i.hasNext();) 53 { 54 Map.Entry entry = (Map.Entry )i.next(); 55 Object key = entry.getKey(); 56 Set value = (Set )entry.getValue(); 57 map.put(key, new HashSet (value)); 58 } 59 } 60 61 64 public void put(Object key, Object o) 65 { 66 Set set = (Set )map.get(key); 67 if (set == null) 68 { 69 set = new HashSet (); 70 map.put(key, set); 71 } 72 set.add(o); 73 } 74 75 78 public Set keySet() 79 { 80 return map.keySet(); 81 } 82 83 86 public void remove(Object key) 87 { 88 map.remove(key); 89 } 90 91 94 public void remove(Object key, Object o) 95 { 96 Set set = (Set )map.get(key); 97 if (set != null) 98 { 99 set.remove(o); 100 if (set.isEmpty()) 101 { 102 map.remove(key); 103 } 104 } 105 } 106 107 110 public boolean contains(Object key, Object o) 111 { 112 Set set = (Set )map.get(key); 113 if (set == null) 114 { 115 return false; 116 } 117 else 118 { 119 return set.contains(o); 120 } 121 } 122 123 126 public Set get(Object key) 127 { 128 return (Set )map.get(key); 129 } 130 131 134 public Iterator iterator(final Object key) 135 { 136 Set set = (Set )map.get(key); 137 if (set == null) 138 { 139 return Collections.EMPTY_SET.iterator(); 140 } 141 else 142 { 143 final Iterator iterator = set.iterator(); 144 return new Iterator () 145 { 146 public boolean hasNext() 147 { 148 return iterator.hasNext(); 149 } 150 public Object next() 151 { 152 return iterator.next(); 153 } 154 public void remove() 155 { 156 iterator.remove(); 157 if (!iterator.hasNext()) 158 { 159 map.remove(key); 160 } 161 } 162 }; 163 } 164 } 165 } 166 | Popular Tags |