1 22 25 26 package ch.ethz.prose.engine; 27 28 import ch.ethz.prose.Insertable; 29 30 public class ListenerList 31 { 32 33 34 public JoinPointListener[] listenerArray; 35 public int nrOfListeners; 36 private int nearestPowerOfTwo; 37 38 public ListenerList() 39 { 40 listenerArray = new JoinPointListener[16]; 41 nearestPowerOfTwo = 16; 42 } 43 44 45 private void ensureCapacity(int newCapacity) 46 { 47 48 if (listenerArray.length >= newCapacity) 50 return; 51 52 nearestPowerOfTwo = 2* nearestPowerOfTwo; 53 54 JoinPointListener[] newListenerArray = new JoinPointListener[nearestPowerOfTwo - 12]; 56 System.arraycopy(listenerArray, 0, newListenerArray, 0, nrOfListeners); 57 listenerArray = newListenerArray; 58 } 59 60 61 public synchronized boolean contains(Object elem) 62 { 63 for (int i = 0; i < nrOfListeners; i++) 64 if ( (elem == null && listenerArray[i] == null ) || 65 (elem != null && elem.equals(listenerArray[i]) ) ) 66 return true; 67 68 return false; 69 } 70 71 static class CrosscutComparator implements java.util.Comparator 72 { 73 public int compare(Object o1, Object o2) 74 { 75 if (o1 instanceof Insertable && o2 instanceof Insertable) 76 return ((Insertable)o1).getPriority() - ((Insertable)o2).getPriority(); 77 else 78 return 0; 79 } 80 81 }; 82 83 84 public synchronized boolean add(JoinPointListener element) 85 { 86 int index = nrOfListeners; 87 CrosscutComparator comparator = new CrosscutComparator(); 88 89 for (index = 0; index < nrOfListeners && 92 comparator.compare(listenerArray[index],element) < 0; index++); 93 94 ensureCapacity(nrOfListeners + 1); 95 System.arraycopy(listenerArray, index, 96 listenerArray, index + 1, nrOfListeners - index); 97 98 listenerArray[index] = element; 99 nrOfListeners++; 100 101 return true; 103 } 104 105 106 107 108 public synchronized boolean remove(Object element) 109 { 110 int indexToRemove = -1; 111 for (int i = 0; i < nrOfListeners; i++) 112 if (element != null && element.equals(listenerArray[i]) ) 113 { 114 indexToRemove = i; 115 remove(indexToRemove); 116 i--; 117 } 118 119 return (indexToRemove == -1); 120 } 121 122 public synchronized boolean isEmpty() 123 { 124 return nrOfListeners == 0; 125 } 126 127 private Object remove(int index) 128 { 129 Object old = listenerArray[index]; if (index < 0 || index > nrOfListeners - 1) 131 throw new IndexOutOfBoundsException (); 132 133 System.arraycopy(listenerArray, index + 1, 134 listenerArray, index, nrOfListeners - index - 1); 135 nrOfListeners --; 136 return old; 137 } 138 139 public String toString() 140 { 141 StringBuffer result = new StringBuffer (); 142 for (int i = 0; i<nrOfListeners; i++) 143 { 144 result.append(listenerArray[i]); 145 if (i != (nrOfListeners -1) ) 146 result.append(","); 147 } 148 149 return result.toString(); 150 } 151 } 152 153 | Popular Tags |