KaiquanMah's picture
this.queue.add(0, element);
3b1bbb3 verified
In the tutorial, a generic class Stack was introduced.
Queue is a data structure similar to a stack.
The difference is that while in a stack, elements are added and removed from the same end, => LIFO
in a queue, 'elements are added to the end but removed from the beginning' (just like how a queue works in real life). => FIFO
Write a generic class Queue<T> with the following properties:
A constructor that does not take any parameters.
A method void add(T element) that adds an element to the front of the queue. => counterintuitive; add to the front
A method T remove(), which removes and returns the last element of the queue. => counterintuitive; but remove from the back
A method boolean hasElements(), which returns true if there is at least one element in the queue.
import java.util.Random;
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
final Random r = new Random();
System.out.println("Testing the Queue class...");
System.out.println("Testing with integer type...");
Queue<Integer> queue = new Queue<>();
int[] numbers = {2, 4, 6, 3, 5};
for (int number : numbers) {
System.out.println("Adding element " + number);
queue.add(number);
}
System.out.println("Removing elements until hasElements == false");
while (queue.hasElements()) {
System.out.println(queue.remove());
}
System.out.println("");
System.out.println("Testing with string type...");
Queue<String> queue2 = new Queue<>();
String[] elements = {"rabbit", "fox", "bear", "elk"};
for (String element : elements) {
System.out.println("Adding element " + element);
queue2.add(element);
}
System.out.println("Removing elements until hasElements == false");
while (queue2.hasElements()) {
System.out.println(queue2.remove());
}
}
}
//ADD
class Queue<T> {
// attributes
private ArrayList<T> queue;
// constructor with no params
public Queue(){
this.queue = new ArrayList<>();
}
// normal ArrayList
// https://stackoverflow.com/questions/12949690/java-arraylist-how-to-add-elements-at-the-beginning
// do not use LinkedList
// LinkedList example from Oracle
// https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html#addFirst(E)
// add element to the front
public void add(T element) {
// for LinkedList
// this.queue.addFirst(element);
// for ArrayList
this.queue.add(0, element);
}
// remove and return last element
public T remove() {
return this.queue.remove(this.queue.size() - 1);
}
public boolean hasElements() {
return this.queue.size() > 0;
}
}
Testing the Queue class...
Testing with integer type...
Adding element 2
Adding element 4
Adding element 6
Adding element 3
Adding element 5
Removing elements until hasElements == false
2
4
6
3
5
Testing with string type...
Adding element rabbit
Adding element fox
Adding element bear
Adding element elk
Removing elements until hasElements == false
rabbit
fox
bear
elk