blob: 8ace7598e27c38e970d6b7656d58053f7aa55924 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.collections;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
/**
* An array list which notifies listeners after one or more items are added
*
* @author bratseth
*/
public class ListenableArrayList<ITEM> extends ArrayList<ITEM> {
private List<Runnable> listeners = null;
public ListenableArrayList() {}
public ListenableArrayList(int initialCapacity) {
super(initialCapacity);
}
@Override
public boolean add(ITEM e) {
boolean result = super.add(e);
notifyListeners();
return result;
}
@Override
public void add(int index, ITEM e) {
super.add(index, e);
notifyListeners();
}
@Override
public boolean addAll(Collection<? extends ITEM> a) {
boolean result = super.addAll(a);
notifyListeners();
return result;
}
@Override
public boolean addAll(int index, Collection<? extends ITEM> a) {
boolean result = super.addAll(index, a);
notifyListeners();
return result;
}
@Override
public ITEM set(int index, ITEM e) {
ITEM result = super.set(index, e);
notifyListeners();
return result;
}
public List<Runnable> listeners() {
if (listeners == null) return Collections.emptyList();
return Collections.unmodifiableList(listeners);
}
/**
* Adds a listener which is invoked whenever elements are added to this.
* This may not be invoked once for each added element.
*/
public void addListener(Runnable listener) {
if (listeners == null)
listeners = new ArrayList<>();
listeners.add(listener);
}
private void notifyListeners() {
if (listeners == null) return;
for (Runnable listener : listeners)
listener.run();
}
}
|