package com.tagtraum.framework.util;
import java.util.*;
/**
* Map that maintains insertion order.
* Does not properly deal with null keys.
*
* @version 1.1beta1, Revision: $id: $
* @author <a href="mailto:hs@tagtraum.com">Hendrik Schreiber</a>
*/
public class OrderedMap {
private Map map;
private List list;
public OrderedMap() {
this.map = new HashMap();
this.list = new ArrayList();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
/**
* This method does NOT return a set that maintains the insertion order.
*/
public Set keySet() {
return Collections.unmodifiableSet(map.keySet());
}
public Object put(Object key, Object value) {
Object oldValue = map.put(key, value);
if (oldValue != null) {
// find the right element
Entry oldEntry = new Entry(key, oldValue);
int i= list.indexOf(oldEntry);
Entry e = (Entry)list.get(i);
e.setIntValue(value);
}
else {
list.add(new Entry(key, value));
}
return oldValue;
}
public Object remove(Object key) {
Object oldValue = map.remove(key);
if (oldValue != null) list.remove(new Entry(key, oldValue));
return oldValue;
}
public Object get(Object key) {
return map.get(key);
}
public void clear() {
map.clear();
list.clear();
}
public boolean isEmpty() {
return map.isEmpty();
}
public List entryList() {
return Collections.unmodifiableList(list);
}
public int size() {
return map.size();
}
private class Entry implements Map.Entry {
private Object key;
private Object value;
public Entry(Object key, Object value) {
this.key = key;
this.value = value;
}
public Object getKey() {
return key;
}
public Object getValue() {
return value;
}
void setIntValue(Object value) {
this.value = value;
}
public Object setValue(Object value) {
throw new UnsupportedOperationException();
}
public boolean equals(Object o) {
if (!(o instanceof Map.Entry)) return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public int hashCode() {
return (key.hashCode()) ^ (value==null ? 0 : value.hashCode());
}
public String toString() {
return getKey() + "=" + getValue();
}
}
}
|