1 11 package org.eclipse.core.databinding.observable.map; 12 13 import java.util.Collections ; 14 import java.util.HashMap ; 15 import java.util.HashSet ; 16 import java.util.Iterator ; 17 import java.util.Map ; 18 import java.util.Set ; 19 20 import org.eclipse.core.databinding.observable.Realm; 21 22 32 public class BidirectionalMap extends ObservableMap { 33 34 private Map valueToElements = new HashMap (); 35 36 private IMapChangeListener mapListener = new IMapChangeListener() { 37 38 public void handleMapChange(MapChangeEvent event) { 39 MapDiff diff = event.diff; 40 for (Iterator it = diff.getAddedKeys().iterator(); it.hasNext();) { 41 Object addedKey = it.next(); 42 addMapping(addedKey, diff.getNewValue(addedKey)); 43 } 44 for (Iterator it = diff.getChangedKeys().iterator(); it.hasNext();) { 45 Object changedKey = it.next(); 46 removeMapping(changedKey, diff.getOldValue(changedKey)); 47 addMapping(changedKey, diff.getNewValue(changedKey)); 48 } 49 for (Iterator it = diff.getRemovedKeys().iterator(); it.hasNext();) { 50 Object removedKey = it.next(); 51 removeMapping(removedKey, diff.getOldValue(removedKey)); 52 } 53 fireMapChange(diff); 54 } 55 }; 56 57 60 public BidirectionalMap(IObservableMap wrappedMap) { 61 super(wrappedMap.getRealm(), wrappedMap); 62 wrappedMap.addMapChangeListener(mapListener); 63 for (Iterator it = wrappedMap.entrySet().iterator(); it.hasNext();) { 64 Map.Entry entry = (Entry) it.next(); 65 addMapping(entry.getKey(), entry.getValue()); 66 } 67 } 68 69 73 private void addMapping(Object key, Object value) { 74 Object elementOrSet = valueToElements.get(value); 75 if (elementOrSet == null) { 76 valueToElements.put(value, key); 77 return; 78 } 79 if (!(elementOrSet instanceof Set )) { 80 elementOrSet = new HashSet (Collections.singleton(elementOrSet)); 81 valueToElements.put(value, elementOrSet); 82 } 83 Set set = (Set ) elementOrSet; 84 set.add(key); 85 } 86 87 91 private void removeMapping(Object functionValue, Object element) { 92 Object elementOrSet = valueToElements.get(functionValue); 93 if (elementOrSet instanceof Set ) { 94 Set set = (Set ) elementOrSet; 95 set.remove(element); 96 if (set.size() == 0) { 97 valueToElements.remove(functionValue); 98 } 99 } else { 100 valueToElements.remove(functionValue); 101 } 102 } 103 104 } 105 | Popular Tags |