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
9
10
11 public abstract class TranslatedObservableCollection<T, U> extends ObservableList<T> {
12
13
14
15
16 Map<Object, T> map = new HashMap<Object, T>();
17
18 public TranslatedObservableCollection(ObservableCollection<U> col) {
19 super(new ArrayList<T>());
20
21
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
30 T val = map.remove(getKeyForObj(elem));
31 remove(val);
32 }
33 }
34 });
35
36
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;
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
59
60
61
62 protected abstract T translate(U obj);
63 }