KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > fri > util > collections > AggregatingHashtable


1 package fri.util.collections;
2
3 import java.util.*;
4 import java.io.*;
5
6 /**
7     A hashtable that holds a list of values instead of a single value for one key.
8     In any case the <i>get(Object)</i> method returns a List (Vector) of values.
9     Every new <i>put()</i> call adds to the list of values. The <i>remove()</i>
10     call removes the whole list of values at once.
11
12     @author Fritz Ritzberger
13 */

14
15 public class AggregatingHashtable extends Hashtable
16 {
17     public AggregatingHashtable() {
18         super();
19     }
20     
21     public AggregatingHashtable(int initialCapacity) {
22         super(initialCapacity);
23     }
24     
25     /**
26         Puts the passed value into a List (Vector) for given key, creates the list when necessary.
27         @return null if list was not yet existent, else the found list.
28     */

29     public Object JavaDoc put(Object JavaDoc key, Object JavaDoc value) {
30         List list = (List) super.get(key);
31         Object JavaDoc ret = null;
32         
33         if (list == null) {
34             list = createAggregationList();
35             super.put(key, list);
36         }
37         else {
38             if (shouldAdd(list, value) == false)
39                 return list;
40             
41             ret = list;
42         }
43
44         list.add(value);
45         return ret;
46     }
47     
48     /** To be overridden for filtering values. */
49     protected boolean shouldAdd(List list, Object JavaDoc value) {
50         return true;
51     }
52
53     /** To be overridden for allocation of special aggregation List types. */
54     protected List createAggregationList() {
55         return new ArrayList();
56     }
57
58     /** Replaces the list of objects for a key by a new list, overriding aggregation. */
59     public void replace(Object JavaDoc key, List newList) {
60         super.put(key, newList);
61     }
62
63
64
65     // Must adjust deserialization as put() will put value lists into newly provided lists
66
private void readObject(ObjectInputStream s)
67         throws IOException, ClassNotFoundException JavaDoc
68     {
69         s.defaultReadObject();
70
71         for (Iterator it = entrySet().iterator(); it.hasNext(); ) {
72             Map.Entry entry = (Map.Entry) it.next();
73             List list = (List) entry.getValue();
74             Object JavaDoc o = list.size() == 1 ? list.get(0) : null; // resolve the list that has been put by super.readObject()
75
if (o instanceof List) { // apache commons MultiHashMap came around with that problem only on JDK 1.2 and 1.3 ?
76
super.put(entry.getKey(), o);
77             }
78         }
79     }
80
81 }
82
Popular Tags