Оцените, пожалуйста, мое решение следующей задачи.
Implement a circular queue of integers of user-specified size using a simple array. Provide routines to initialize(), enqueue() and dequeue() the queue. Make it thread safe.
Please do not to use existing class libraries for this question.
Мое решение
/**
* Thread safe Circular queue implementation
*/
public class CircularQueue {
private int[] internalContainer;
private int lastElementIndex;
/**
* Public constructor
* @param size initial capacity
*/
public CircularQueue(int size) {
if(size < 1) {
throw new IllegalArgumentException("size cannot be negative or zero");
}
internalContainer = new int[ size ];
lastElementIndex = 0;
}
/**
* Initialize queue with elements
* @throws IllegalStateException if input elements more than queue capacity
*/
public synchronized void initialize(int... elements) {
if(elements == null) {
throw new NullPointerException("elements parameter cannot be null");
}
else if(elements.length > internalContainer.length) {
throw new IllegalStateException("elements amount is more than queue capacity");
}
lastElementIndex = elements.length - 1;
arrayCopy(elements, 0, internalContainer, 0, elements.length);
}
/**
* Adds element to the end of the queue
* Throws:
* IllegalStateException if the element cannot be added at this time due to capacity restrictions
*/
public synchronized void enqueue(int element) {
if(lastElementIndex + 1 == internalContainer.length) {
throw new IllegalStateException("queue is full");
}
internalContainer [ lastElementIndex + 1 ] = element;
++lastElementIndex;
}
/**
* Removes and returns the integer at the beginning of the queue
* Throws:
* IllegalStateException if the queue is empty
*/
public synchronized int dequeue() {
if(lastElementIndex == -1) {
throw new IllegalStateException("no elements in queue");
}
--lastElementIndex;
int result = internalContainer[0];
arrayCopy(internalContainer, 1, internalContainer, 0, internalContainer.length);
return result;
}
private void arrayCopy(int[] src, int srcPos, int[] dest, int destPos, int length) {
for (int i = 0; (i < length) && ((destPos + i) < dest.length) && ((srcPos + i) < src.length); i++) {
dest [ destPos + i ] = src[ srcPos + i ];
}
}
}
30.06.08 13:36: Перенесено модератором из 'Java' — Blazkowicz
08.07.08 20:42: Перенесено модератором из 'Архитектура программного обеспечения' — Кодт
08.07.08 20:43: Перенесено модератором из 'Алгоритмы' — пардон, не на то нажал — Кодт