-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBoundedQueue.java
More file actions
84 lines (74 loc) · 2.24 KB
/
BoundedQueue.java
File metadata and controls
84 lines (74 loc) · 2.24 KB
1
2
3
4
5
6
7
8
9
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
78
79
80
81
82
83
84
// Introduction to Software Testing
// Authors: Paul Ammann & Jeff Offutt
// Chapter 3, page ??
public class BoundedQueue
{
// Overview: a BoundedQueue is a mutable, bounded FIFO data structure
// of fixed size , with size being set in the constructor
// A typical Queue is [], [o1], or [o1, o2], where neither o1 nor o2
// are ever null. Older elements are listed before newer ones.
private final Object[] elements;
private int size, front, back;
private final int capacity;
public BoundedQueue (int capacity)
{
if (capacity < 0)
throw new IllegalArgumentException ("BoundedQueue.constructor");
this.capacity = capacity;
elements = new Object [capacity];
size = 0; front = 0; back = 0;
}
public void enQueue (Object o)
throws NullPointerException, IllegalStateException
{ // Modifies: this
// Effects: If argument is null throw NullPointerException
// else if this is full, throw IllegalStateException,
// else make o the newest element of this
if (o == null)
throw new NullPointerException ("BoundedQueue.enQueue");
else if (size == capacity)
throw new IllegalStateException ("BoundedQueue.enQueue");
else
{
size++;
elements [back] = o;
back = (back+1) % capacity;
}
}
public Object deQueue () throws IllegalStateException
{ // Modifies: this
// Effects: If queue is empty, throw IllegalStateException,
// else remove and return oldest element of this
if (size == 0)
throw new IllegalStateException ("BoundedQueue.deQueue");
else
{
size--;
Object o = elements [ (front % capacity) ];
elements [front] = null;
front = (front+1) % capacity;
return o;
}
}
public boolean isEmpty()
{
return (size == 0);
}
public boolean isFull()
{
return (size == capacity);
}
public String toString()
{
String result = "[";
for (int i = 0; i < size; i++)
{
result += elements[ (front + i) % capacity ] . toString();
if (i < size -1) {
result += ", ";
}
}
result += "]";
return result;
}
}