-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericsQueue.java
More file actions
79 lines (78 loc) · 2.52 KB
/
Copy pathGenericsQueue.java
File metadata and controls
79 lines (78 loc) · 2.52 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
// A generic, fixed-size queue class.
class GenQueue<T> implements IGenQ<T> {
private T[] q; // this array holds the queue
private int putloc, getloc; // the put and get indices
// Construct an empty queue with the given array.
public GenQueue(T[] aRef) {
q = aRef;
putloc = getloc = 0;
}
// Put an item into the queue.
public void put(T obj) throws QueueFullException {
if(putloc == q.length)
throw new QueueFullException(q.length);
q[putloc++] = obj;
}
// Get a character from the queue.
public T get() throws QueueEmptyException {
if(getloc == putloc)
throw new QueueEmptyException();
return q[getloc++];
}
}
public class GenericsQueue {
public static void main(String[] args) {
// Create an integer queue.
Integer[] iStore = new Integer[10];
GenQueue<Integer> q = new GenQueue<Integer>(iStore);
Integer iVal;
System.out.println("Demonstrate a queue of Integers.");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + i + " to q.");
q.put(i); // add integer value to q
}
}
catch (QueueFullException exc) {
System.out.println(exc);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Integer from q: ");
iVal = q.get();
System.out.println(iVal);
}
}
catch (QueueEmptyException exc) {
System.out.println(exc);
}
System.out.println();
// Create a Double queue.
Double[] dStore = new Double[10];
GenQueue<Double> q2 = new GenQueue<Double>(dStore);
Double dVal;
System.out.println("Demonstrate a queue of Doubles.");
try {
for (int i = 0; i < 5; i++) {
System.out.println("Adding " + (double)i/2 +
" to q2.");
q2.put((double)i/2); // add double value to q2
}
}
catch (QueueFullException exc) {
System.out.println(exc);
}
System.out.println();
try {
for (int i = 0; i < 5; i++) {
System.out.print("Getting next Double from q2: ");
dVal = q2.get();
System.out.println(dVal);
}
}
catch (QueueEmptyException exc) {
System.out.println(exc);
}
}
}