01: /*
02: * FindBugs - Find Bugs in Java programs
03: * Copyright (C) 2006, University of Maryland
04: *
05: * This library is free software; you can redistribute it and/or
06: * modify it under the terms of the GNU Lesser General Public
07: * License as published by the Free Software Foundation; either
08: * version 2.1 of the License, or (at your option) any later version.
09: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library; if not, write to the Free Software
17: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18: */
19:
20: package edu.umd.cs.findbugs.util;
21:
22: import java.util.Collection;
23: import java.util.HashMap;
24: import java.util.Map;
25:
26: import edu.umd.cs.findbugs.TigerSubstitutes;
27:
28: /**
29: * @author pugh
30: */
31: public class MultiMap<K, V> {
32: final Class<? extends Collection<V>> containerClass;
33:
34: @SuppressWarnings("unchecked")
35: public MultiMap(Class<? extends Collection> c) {
36: containerClass = (Class<? extends Collection<V>>) c;
37: }
38:
39: private Collection<V> makeCollection() {
40: try {
41: return containerClass.newInstance();
42: } catch (InstantiationException e) {
43: throw new RuntimeException(e);
44: } catch (IllegalAccessException e) {
45: throw new RuntimeException(e);
46: }
47: }
48:
49: Map<K, Collection<V>> map = new HashMap<K, Collection<V>>();
50:
51: public Collection<? extends K> keySet() {
52: return map.keySet();
53: }
54:
55: public void clear() {
56: map.clear();
57: }
58:
59: public void add(K k, V v) {
60: Collection<V> s = map.get(k);
61: if (s == null) {
62: s = makeCollection();
63: map.put(k, s);
64: }
65: s.add(v);
66: }
67:
68: public void remove(K k, V v) {
69: Collection<V> s = map.get(k);
70: if (s != null) {
71: s.remove(v);
72: if (s.isEmpty())
73: map.remove(k);
74: }
75: }
76:
77: public void removeAll(K k) {
78: map.remove(k);
79: }
80:
81: public Collection<V> get(K k) {
82: Collection<V> s = map.get(k);
83: if (s != null)
84: return s;
85: return TigerSubstitutes.emptySet();
86: }
87:
88: }
|