1 45 package org.exolab.jms.common.util; 46 47 import java.util.Comparator ; 48 import java.util.Vector ; 49 50 51 60 public class OrderedQueue { 61 62 65 private Vector _queue = null; 66 67 70 private Comparator _comparator = null; 71 72 79 public OrderedQueue(Comparator comparator) { 80 _comparator = comparator; 81 _queue = new Vector (); 82 } 83 84 90 public synchronized void add(Object object) { 91 92 if (_queue.size() == 0) { 93 _queue.addElement(object); 95 } else { 96 int start = 0; 97 int end = _queue.size() - 1; 98 99 if (_comparator.compare(object, 100 _queue.firstElement()) < 0) { 101 _queue.insertElementAt(object, 0); 103 } else if (_comparator.compare(object, 104 _queue.lastElement()) > 0) { 105 _queue.addElement(object); 107 } else { 108 while (true) { 110 int midpoint = start + (end - start) / 2; 111 if (((end - start) % 2) != 0) { 112 midpoint++; 113 } 114 115 int result = _comparator.compare( 116 object, _queue.elementAt(midpoint)); 117 118 if (result == 0) { 119 _queue.insertElementAt(object, midpoint); 120 break; 121 } else if ((start + 1) == end) { 122 _queue.insertElementAt(object, end); 125 break; 126 } else { 127 if (result > 0) { 128 start = midpoint; 130 } else { 131 end = midpoint; 133 } 134 } 135 } 136 } 137 } 138 } 139 140 146 public synchronized boolean remove(Object object) { 147 return _queue.remove(object); 148 } 149 150 153 public synchronized void clear() { 154 _queue.clear(); 155 } 156 157 162 public int size() { 163 return _queue.size(); 164 } 165 166 171 public Object firstElement() { 172 return _queue.firstElement(); 173 } 174 175 181 public synchronized Object removeFirstElement() { 182 return _queue.remove(0); 183 } 184 185 } 186 187 | Popular Tags |