Here you'll take a look at how you could go about creating your own custom Queue class, which is actually pretty quick when you use the LinkedList class that you've already created. If you do not have your custom LinkedList class available, you can swap it out for the java.util.LinkedList class.
// Queue is generic so it can hold any object type
public class CustomQueue<V> {
// create a LinkedList for to use as
// the underlying data structure
// keep this private so it can't be modified
// outside of this class
private LinkedList<V> list = new LinkedList<>();
/**
* Adds an item to the Queue
* @param item to be added
*/
public void enqueue(V item) {
// insert item into front of list
list.addLast(item);
}
/**
* Removes an item from the Queue
* @return the removed item
*/
public V dequeue() {
if (list.isEmpty()){
return null;
// you could also throw an exception here
}
try {
// get item from the front of the Queue
V item = list.removeFirst();
// return first item that you got just above
return item;
} catch (NullPointerException ex) {
return null;
}
}
/**
* Removes true if the Queue is empty false
* if the queue is not empty
* @return boolean isEmpty
*/
public boolean isEmpty(){
// surface this method to be called for functionality
return list.isEmpty();
}
}
That's another abstract data structure in the bag! Going quickly, isn't it? ;)
Summary: Example of a Queue in Java
- This lesson provides an example of a custom queue class
- The example branches off the previously created
CustomLinkedList - The example creates three methods
enqueue()dequeue()isEmpty()****