/** * Sets the capacity of the queue equal to its current size. * This eliminates any wasted space in the array used to implement * the queue. */ public void trimToSize() { resize(_size); }
/** * Ensures that the capacity of the queue is not less than the * specified value. * The capacity is the number of entries that the queue can hold without * increasing the length of the array used to implement the queue. * <p> * This method may be used to reduce the cost of adding a large number * of entries to the queue, when that number of entries is known in * advance. * @param capacity the capacity. */ public void ensureCapacity(int capacity) { if (capacity<_length) capacity = _length; resize(capacity); }
/** * Adds the specified entry to the back of the queue. * Before addition, if the size of the queue equals its capacity, * then the capacity of the queue is doubled. * @param e the entry. */ public void add(E e) { // If no space is left in the array, double its size. if (_size==_length) resize(_size*2); // Index of entry to be added at the back of the queue. // This index is computed modulo the length of the array. int index = _first+_size; if (index>=_length) index -= _length; // Add the entry at the back of the queue. _array[index] = e; ++_size; }
/** * Removes and returns the entry from the front of the queue. * After removal, if the size of the queue is less than one third * its capacity, then the capacity is set to be twice that size. * (Note that the capacity shrinks more slowly than it grows.) * @return the entry. */ public E remove() { // Ensure the queue contains at least one entry. if (_size==0) throw new NoSuchElementException(); // Remove the first entry from the queue. If the entry removed // is at the end of the array, the next entry is at the beginning. @SuppressWarnings("unchecked") E e = (E)_array[_first]; ++_first; if (_first==_length) _first = 0; --_size; // If two-thirds of the space in the array is unused, shrink it. // However, assuming that entries will again be added to the queue, // keep half the unused space. By shrinking the array more slowly // than we grow it, we reduce the likelihood of spurious grow-shrink // cycles. if (_size*3<_length) resize(_size*2); // Return the entry removed. return e; }