1 | /** | | 1 | /** |
2 | * Adds elements from collection without duplicates. | | 2 | * Update a collection using a minimal update strategy and updating the |
3 | */ | | 3 | * collection in place. This can be used with the JMI "live" semantic |
4 | private void addCollection(Collection c, Collection v) { | | 4 | * collections to update the model in place. Order of processing is to first |
5 | for (Object o : c) { | | 5 | * remove all obsolete elements from the collection and then add all new |
6 | if (!v.contains(o)) { | | 6 | * elements. |
7 | v.add(o); | | 7 | * |
8 | } | | 8 | * @param base |
9 | } | | 9 | * the base collection to be updated |
10 | } | | 10 | * @param updates |
| | | 11 | * desired end state of collection |
| | | 12 | */ |
| | | 13 | static void update(Collection base, Collection updates) { |
| | | 14 | if (updates == null) { |
| | | 15 | base.clear(); |
| | | 16 | return; |
| | | 17 | } |
| | | 18 | Collection toBeRemoved = new ArrayList(); |
| | | 19 | Collection toBeAdded = new ArrayList(); |
| | | 20 | |
| | | 21 | Iterator oldIt = base.iterator(); |
| | | 22 | while (oldIt.hasNext()) { |
| | | 23 | Object obj = oldIt.next(); |
| | | 24 | if (!updates.contains(obj)) { |
| | | 25 | toBeRemoved.add(obj); |
| | | 26 | } |
| | | 27 | } |
| | | 28 | Iterator newIt = updates.iterator(); |
| | | 29 | while (newIt.hasNext()) { |
| | | 30 | Object obj = newIt.next(); |
| | | 31 | if (!base.contains(obj)) { |
| | | 32 | toBeAdded.add(obj); |
| | | 33 | } |
| | | 34 | } |
| | | 35 | |
| | | 36 | base.removeAll(toBeRemoved); |
| | | 37 | base.addAll(toBeAdded); |
| | | 38 | } |