source: josm/trunk/src/org/openstreetmap/josm/tools/ListeningCollection.java@ 12676

Last change on this file since 12676 was 12269, checked in by Don-vip, 7 years ago

sonar - squid:S1319 - Declarations should use Java collection interfaces such as "List" rather than specific implementation classes such as "ArrayList"

  • Property svn:eol-style set to native
File size: 2.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.util.AbstractCollection;
5import java.util.Iterator;
6import java.util.List;
7
8/**
9 * This is a proxy of a collection that notifies a listener on every collection change
10 * @author Michael Zangl
11 *
12 * @param <T> The entry type
13 * @since 12267 (extracted from GpxData)
14 * @since 12156
15 */
16public class ListeningCollection<T> extends AbstractCollection<T> {
17 private final List<T> base;
18 private final Runnable runOnModification;
19
20 /**
21 * Constructs a new {@code ListeningCollection}.
22 * @param base base collection
23 * @param runOnModification runnable run at each modification
24 * @since 12269
25 */
26 public ListeningCollection(List<T> base, Runnable runOnModification) {
27 this.base = base;
28 this.runOnModification = runOnModification;
29 }
30
31 @Override
32 public final Iterator<T> iterator() {
33 Iterator<T> it = base.iterator();
34 return new Iterator<T>() {
35 private T object;
36
37 @Override
38 public boolean hasNext() {
39 return it.hasNext();
40 }
41
42 @Override
43 public T next() {
44 object = it.next();
45 return object;
46 }
47
48 @Override
49 public void remove() {
50 if (object != null) {
51 removed(object);
52 object = null;
53 }
54 it.remove();
55 }
56 };
57 }
58
59 @Override
60 public final int size() {
61 return base.size();
62 }
63
64 @Override
65 @SuppressWarnings("unchecked")
66 public final boolean remove(Object o) {
67 boolean remove = base.remove(o);
68 if (remove) {
69 removed((T) o);
70 }
71 return remove;
72 }
73
74 @Override
75 public final boolean add(T e) {
76 boolean add = base.add(e);
77 added(e);
78 return add;
79 }
80
81 /**
82 * Called when an object is removed.
83 * @param object the removed object
84 */
85 protected void removed(T object) {
86 runOnModification.run();
87 }
88
89 /**
90 * Called when an object is added.
91 * @param object the added object
92 */
93 protected void added(T object) {
94 runOnModification.run();
95 }
96}
Note: See TracBrowser for help on using the repository browser.