6 * A HashMap subclass which adds multiple values with the same key to
7 * a List of values. Single values remain single keys, obviating the
8 * need to cart around single-element Lists.
10 * Copyright (C) 2001 Eric D. Friedman (eric@hfriedman.rdsl.lmi.net)
12 * This program is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, write to the Free Software
24 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26 * Created: Tue Aug 14 19:36:50 2001
28 * @author Eric D. Friedman
29 * @version $Id: MultiValueMap.java,v 1.1 2001/08/15 06:31:27 eric Exp $
32 public class MultiValueMap extends HashMap {
33 public MultiValueMap () {
38 * Convenience method for retrieving the value for
39 * <code>key</code> as a List, even when there is only a single
40 * value for that key in the map. The EMPTY_LIST is returned when
41 * no value is found for <code>key</code> making null checks
44 * @param key an <code>Object</code> value
45 * @return a <code>List</code> value
47 public List getAsList(Object key) {
48 if (containsKey(key)) {
50 if (o instanceof List) {
53 return Arrays.asList(new Object[] { o });
56 return Collections.EMPTY_LIST;
61 * inserts value into the map for key as a single element or, if
62 * values already exist, as an entry in key's list.
64 * @param key an <code>Object</code> value
65 * @param value an <code>Object</code> value
68 public Object put(Object key, Object value) {
69 if (containsKey(key)) {
70 Object other = get(key);
71 if (other instanceof List) {
72 ((List)other).add(value);
74 List l = new ArrayList();