View Javadoc

1   package cz.cuni.amis.utils.collections;
2   
3   import java.util.ArrayList;
4   import java.util.HashMap;
5   import java.util.Map;
6   
7   /**
8    * Translates one observable collection into another
9    * @author ik
10   */
11  public abstract class TranslatedObservableCollection<T, U> extends ObservableList<T> {
12  
13      /**
14       * Holds mapping between original objects and the translated one.
15       */
16      Map<Object, T> map = new HashMap<Object, T>();
17  
18      public TranslatedObservableCollection(ObservableCollection<U> col) {
19          super(new ArrayList<T>());
20  
21          // listen for changes
22          col.addCollectionListener(new ElementListener<U>() {
23  
24              @Override
25              public void elementChanged(U elem, boolean added) {
26                  if (added) {
27                      insert(elem);
28                  } else {
29                      // remove element
30                      T val = map.remove(getKeyForObj(elem));
31                      remove(val);
32                  }
33              }
34          });
35  
36          // import existing items
37          for (U val : col) {
38              insert(val);
39          }
40  
41      }
42  
43      protected synchronized void insert(U elem) {
44          if (map.containsKey(getKeyForObj(elem))) return; // will not insert already present item
45      	T val = translate(elem);
46          if (val != null) {
47              map.put(getKeyForObj(elem), val);
48              add(val);
49          }
50  
51      }
52  
53      protected Object getKeyForObj(U elem) {
54          return elem;
55      }
56  
57      /**
58       * Translates object from wrapped collection into this collection.
59       * @param obj object to be translated
60       * @return the translated object, null if the object shouldn't be added to the collection
61       */
62      protected abstract T translate(U obj);
63  }