AuD
Lecture 'Algorithmen und Datenstrukturen' (code examples)
Queue.java
Go to the documentation of this file.
1package aud;
2
4import java.util.NoSuchElementException;
5
10//@<queue:class
11public class Queue<T> extends AbstractQueue<T> {
12
13 T[] data_;
14 int head_ = 0;
15 int tail_ = 0;
16 //@>queue:class
17
18 static final int DEFAULT_SIZE = 16;
19
21 public Queue() {
22 this(DEFAULT_SIZE);
23 }
25 @SuppressWarnings("unchecked")
26 //@<queue:ctor
27 public Queue(int capacity) {
28 data_=(T[]) new Object[capacity];
29 head_=tail_=0;
30 }
31 //@>queue:ctor
32
33 @Override
34 //@<queue:empty
35 public boolean is_empty() {
36 return head_==tail_;
37 }
38 //@>queue:empty
39
40 @Override
41 //@<queue:front
42 public T front() {
43 if (is_empty())
44 throw new NoSuchElementException();
45 return data_[head_];
46 }
47 //@>queue:front
48
49 //@<queue:dequeue
50 @Override public T dequeue() {
51 if (is_empty())
52 throw new NoSuchElementException();
53 T obj=data_[head_];
54 data_[head_]=null; // "free" entry (for GC)
55 head_=(head_+1)%data_.length;
56 return obj;
57 }
58 //@>queue:dequeue
59
60 @Override
61 //@<queue:enqueue1
62 public void enqueue(T x) {
63 int newtail=(tail_+1)%data_.length;
64
65 if (newtail!=head_) {
66 // no "overrun" we just advance an index.
67 data_[tail_]=x;
68 tail_=newtail;
69 }
70 else {
71 //@>queue:enqueue1
72 //System.err.println("enlarge buffer of size "+data_.length);
73
74 // detected "overrun": the new head "hits" tail --
75 // This means the alloacted buffer data is too small!
76
77 // get larger buffer q
78 Queue<T> q=new Queue<T>(data_.length*2);
79
80 // copy data into q
81 while (!is_empty())
82 q.enqueue(dequeue());
83 q.enqueue(x);
84
85 // "steal" state of temporary object q
86 data_=q.data_;
87 head_=q.head_;
88 tail_=q.tail_;
89 assert(head_==0 && tail_<data_.length);
90 }
91 }
92
151 @Override
152 public String toString() {
153 if (is_empty())
154 return "<";
155
156 String s="";
157
158 int t=(tail_+data_.length-1)%data_.length;
159 for (;;) {
160 s=data_[t]+"<"+s;
161 if (t==head_)
162 break;
163 t=(t+data_.length-1)%data_.length;
164 }
165 return s;
166 }
167}
Implementation of AbstractQueue as a (dynamically resized) circular buffer based on array.
Definition: Queue.java:11
void enqueue(T x)
Enqueue element at end of queue.
Definition: Queue.java:62
boolean is_empty()
Is queue empty?
Definition: Queue.java:35
String toString()
Get string representation.
Definition: Queue.java:152
T dequeue()
Remove front element from queue.
Definition: Queue.java:50
Queue()
create empty queue
Definition: Queue.java:21
T front()
Get front element of queue.
Definition: Queue.java:42
Interface for an ADT queue.
abstract data types
AuD lecture: Data structures, algorithms, examples.