55import java .util .function .Consumer ;
66
77/**
8- * A set of listeners of type {@code T}.
8+ * An ordered set of listeners of type {@code T}.
99 *
1010 * @param <T>
1111 * listener type
1212 */
1313public interface Listeners < T >
1414{
1515 /**
16- * Add a listener to this set.
16+ * Add a listener to the end of this set.
1717 *
1818 * @param listener
1919 * the listener to add.
@@ -22,6 +22,19 @@ public interface Listeners< T >
2222 */
2323 boolean add ( final T listener );
2424
25+ /**
26+ * Insert a listener at the specified position in this set.
27+ * The position {@code index} is clamped to the range [0..size].
28+ *
29+ * @param index
30+ * index at which to add the specified listener
31+ * @param listener
32+ * the listener to add
33+ * @return {@code true} if the listener was added. {@code false} if it was
34+ * already present.
35+ */
36+ boolean add ( final int index , final T listener );
37+
2538 /**
2639 * Removes a listener from this set.
2740 *
@@ -77,6 +90,18 @@ public boolean add( final T listener )
7790 return false ;
7891 }
7992
93+ @ Override
94+ public boolean add ( final int index , final T listener )
95+ {
96+ if ( !list .contains ( listener ) )
97+ {
98+ list .add ( clamp ( index , 0 , list .size () ), listener );
99+ onAdd .accept ( listener );
100+ return true ;
101+ }
102+ return false ;
103+ }
104+
80105 @ Override
81106 public boolean remove ( final T listener )
82107 {
@@ -87,6 +112,11 @@ public ArrayList< T > listCopy()
87112 {
88113 return new ArrayList <>( list );
89114 }
115+
116+ static int clamp ( int value , int min , int max )
117+ {
118+ return Math .min ( max , Math .max ( min , value ) );
119+ }
90120 }
91121
92122 /**
@@ -111,6 +141,12 @@ public synchronized boolean add( final T listener )
111141 return super .add ( listener );
112142 }
113143
144+ @ Override
145+ public synchronized boolean add ( final int index , final T listener )
146+ {
147+ return super .add ( index , listener );
148+ }
149+
114150 @ Override
115151 public synchronized boolean remove ( final T listener )
116152 {
0 commit comments