01: /*
02: * Copyright (C) 2005 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 06. February 2005 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.core.util;
13:
14: import java.util.ArrayList;
15: import java.util.Arrays;
16: import java.util.Collection;
17: import java.util.Collections;
18: import java.util.HashMap;
19: import java.util.Iterator;
20: import java.util.List;
21: import java.util.Map;
22: import java.util.Set;
23:
24: public class OrderRetainingMap extends HashMap {
25:
26: private ArraySet keyOrder = new ArraySet();
27: private List valueOrder = new ArrayList();
28:
29: public OrderRetainingMap() {
30: super ();
31: }
32:
33: public OrderRetainingMap(Map m) {
34: super ();
35: for (final Iterator iter = m.entrySet().iterator(); iter
36: .hasNext();) {
37: final Map.Entry entry = (Map.Entry) iter.next();
38: put(entry.getKey(), entry.getValue());
39: }
40: }
41:
42: public Object put(Object key, Object value) {
43: int idx = keyOrder.lastIndexOf(key);
44: if (idx < 0) {
45: keyOrder.add(key);
46: valueOrder.add(value);
47: } else {
48: valueOrder.set(idx, value);
49: }
50: return super .put(key, value);
51: }
52:
53: public Object remove(Object key) {
54: int idx = keyOrder.lastIndexOf(key);
55: if (idx != 0) {
56: keyOrder.remove(idx);
57: valueOrder.remove(idx);
58: }
59: return super .remove(key);
60: }
61:
62: public Collection values() {
63: return Collections.unmodifiableList(valueOrder);
64: }
65:
66: public Set keySet() {
67: return Collections.unmodifiableSet(keyOrder);
68: }
69:
70: public Set entrySet() {
71: Map.Entry[] entries = new Map.Entry[size()];
72: for (Iterator iter = super .entrySet().iterator(); iter
73: .hasNext();) {
74: Map.Entry entry = (Map.Entry) iter.next();
75: entries[keyOrder.indexOf(entry.getKey())] = entry;
76: }
77: Set set = new ArraySet();
78: set.addAll(Arrays.asList(entries));
79: return Collections.unmodifiableSet(set);
80: }
81:
82: private static class ArraySet extends ArrayList implements Set {
83: }
84: }
|