Project

General

Profile

Download (2.28 KB) Statistics
| Branch: | Tag: | Revision:
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2010 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials
4
 * are made available under the terms of the Eclipse Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/epl-v10.html
7
 *
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.draw2d.internal;
12

    
13
import java.util.ArrayList;
14
import java.util.HashMap;
15
import java.util.Iterator;
16
import java.util.List;
17

    
18
public class MultiValueMap {
19
	private HashMap map = new HashMap();
20

    
21
	public ArrayList get(Object key) {
22
		Object value = map.get(key);
23
		if (value == null)
24
			return null;
25

    
26
		if (value instanceof ArrayList)
27
			return (ArrayList) value;
28
		ArrayList v = new ArrayList(1);
29
		v.add(value);
30
		return v;
31
	}
32

    
33
	public void put(Object key, Object value) {
34
		Object existingValues = map.get(key);
35
		if (existingValues == null) {
36
			map.put(key, value);
37
			return;
38
		}
39
		if (existingValues instanceof ArrayList) {
40
			ArrayList v = (ArrayList) existingValues;
41
			if (!v.contains(value))
42
				v.add(value);
43
			return;
44
		}
45
		if (existingValues != value) {
46
			ArrayList v = new ArrayList(2);
47
			v.add(existingValues);
48
			v.add(value);
49
			map.put(key, v);
50
		}
51
	}
52

    
53
	public int remove(Object key, Object value) {
54
		Object existingValues = map.get(key);
55
		if (existingValues != null) {
56
			if (existingValues instanceof ArrayList) {
57
				ArrayList v = (ArrayList) existingValues;
58
				int result = v.indexOf(value);
59
				if (result == -1)
60
					return -1;
61
				v.remove(result);
62
				if (v.isEmpty())
63
					map.remove(key);
64
				return result;
65
			}
66
			if (map.remove(key) != null)
67
				return 0;
68
		}
69
		return -1;
70
	}
71

    
72
	public Object removeValue(Object value) {
73
		Iterator iter = map.values().iterator();
74
		Object current;
75
		while (iter.hasNext()) {
76
			current = iter.next();
77
			if (value.equals(current)) {
78
				iter.remove();
79
				return value;
80
			} else if (current instanceof List) {
81
				if (((List) current).remove(value)) {
82
					if (((List) current).isEmpty())
83
						iter.remove();
84
					return value;
85
				}
86
			}
87
		}
88
		return null;
89
	}
90

    
91
	public int size() {
92
		return map.size();
93
	}
94
}
(1-1/2)