diff -r 62043f5f7c67 -r 0e29eec2df5c project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/netplay/ObservableLinkedHashMap.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/project_files/Android-build/SDL-android-project/src/org/hedgewars/hedgeroid/netplay/ObservableLinkedHashMap.java Thu Jul 19 18:58:18 2012 +0200 @@ -0,0 +1,72 @@ +package org.hedgewars.hedgeroid.netplay; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +/** + * A map of items, sorted by time of insertion (earliest first). + * Observers can be notified about insertions, deletions and changes (which don't change the order). + * This is useful for e.g. the lists of current rooms and players, because it allows easy addition + * and removal of entries on the one side, as well as reaction to these events by UI elements. + */ +public class ObservableLinkedHashMap { + private LinkedHashMap map = new LinkedHashMap(); + private List> observers = new LinkedList>(); + + public Collection getValues() { + return Collections.unmodifiableCollection(map.values()); + } + + public Map getMap() { + return Collections.unmodifiableMap(map); + } + + public void observe(Observer observer) { + observers.add(observer); + } + + public void unobserve(Observer observer) { + observers.remove(observer); + } + + // TODO ugh + public void clear() { + while(!map.isEmpty()) { + remove(map.keySet().iterator().next()); + } + } + + public void put(K key, V value) { + V oldValue = map.put(key, value); + Map unmodifiableMap = Collections.unmodifiableMap(map); + if(oldValue != null) { + for(Observer o : observers) { + o.itemReplaced(unmodifiableMap, key, oldValue, value); + } + } else { + for(Observer o : observers) { + o.itemAdded(unmodifiableMap, key, value); + } + } + } + + public void remove(K key) { + V oldValue = map.remove(key); + if(oldValue != null) { + Map unmodifiableMap = Collections.unmodifiableMap(map); + for(Observer o : observers) { + o.itemRemoved(unmodifiableMap, key, oldValue); + } + } + } + + public static interface Observer { + void itemAdded(Map map, K key, V value); + void itemRemoved(Map map, K key, V oldValue); + void itemReplaced(Map map, K key, V oldValue, V newValue); + } +}