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

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

sonar - fix various recent violations

  • 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.ArrayList;
6import java.util.Iterator;
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 ArrayList<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 */
25 public ListeningCollection(ArrayList<T> base, Runnable runOnModification) {
26 this.base = base;
27 this.runOnModification = runOnModification;
28 }
29
30 @Override
31 public final Iterator<T> iterator() {
32 Iterator<T> it = base.iterator();
33 return new Iterator<T>() {
34 private T object;
35
36 @Override
37 public boolean hasNext() {
38 return it.hasNext();
39 }
40
41 @Override
42 public T next() {
43 object = it.next();
44 return object;
45 }
46
47 @Override
48 public void remove() {
49 if (object != null) {
50 removed(object);
51 object = null;
52 }
53 it.remove();
54 }
55 };
56 }
57
58 @Override
59 public final int size() {
60 return base.size();
61 }
62
63 @Override
64 @SuppressWarnings("unchecked")
65 public final boolean remove(Object o) {
66 boolean remove = base.remove(o);
67 if (remove) {
68 removed((T) o);
69 }
70 return remove;
71 }
72
73 @Override
74 public final boolean add(T e) {
75 boolean add = base.add(e);
76 added(e);
77 return add;
78 }
79
80 /**
81 * Called when an object is removed.
82 * @param object the removed object
83 */
84 protected void removed(T object) {
85 runOnModification.run();
86 }
87
88 /**
89 * Called when an object is added.
90 * @param object the added object
91 */
92 protected void added(T object) {
93 runOnModification.run();
94 }
95}
Note: See TracBrowser for help on using the repository browser.