01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
package horstmann.ch03_queue;
/**
A first-in, first-out bounded collection of messages.
*/
public class MessageQueue
{
/**
Constructs an empty message queue.
@param capacity the maximum capacity of the queue
<p><b>Precondition:</b> capacity > 0
*/
public MessageQueue(int capacity)
{
elements = new Message[capacity];
count = 0;
head = 0;
tail = 0;
}
/**
Remove message at head.
@return the message that has been removed from the queue
<p><b>Precondition:</b> size() > 0
*/
public Message remove()
{
Message r = elements[head];
head = (head + 1) % elements.length;
count--;
return r;
}
/**
Append a message at tail.
@param aMessage the message to be appended
<p><b>Precondition:</b> !isFull();
*/
public void add(Message aMessage)
{
elements[tail] = aMessage;
tail = (tail + 1) % elements.length;
count++;
}
/**
Get the total number of messages in the queue.
@return the total number of messages in the queue
*/
public int size()
{
return count;
}
/**
Checks whether this queue is full
@return true if the queue is full
*/
public boolean isFull()
{
return count == elements.length;
}
/**
Get message at head.
@return the message that is at the head of the queue
<p><b>Precondition:</b> size() > 0
*/
public Message peek()
{
return elements[head];
}
private Message[] elements;
private int head;
private int tail;
private int count;
}
|