Queue interface

PHOTO EMBED

Sun Dec 25 2022 20:59:46 GMT+0000 (Coordinated Universal Time)

Saved by @prettyleka #java #generics #queue

//collection that stores elements that can be accessed at some later point to process (like waiting in line at the bank teller). A Queue accesses elements in a (usually) First In First Out (FIFO) manner where elements are inserted at the tail (back) of the collection and removed from the head (front).
//A Queue has two types of access methods for inserting, removing, and getting but not removing the head of the Queue.
//The following methods throw an exception when:
//add() - there is no space for the element
//remove() - there are no elements to remove
//element() - there are no elements to get
//The following methods return a special value:
//offer() - false there is no space for the element
//poll() - null there are no elements to remove
//peek() - null there are no elements to get
//The methods that return a special value should be used when working with a statically sized Queue and the exception throwing methods when using a dynamic Queue.

Queue<String> stringQueue = new LinkedList<>();
stringQueue.add("Mike"); // true - state of queue -> "Mike"
stringQueue.offer("Jeff"); // true - state of queue -> "Mike", "Jeff" 
 
String a = stringQueue.remove() // Returns "Mike" - state of queue -> 1
String b = stringQueue.poll() // Returns "Jeff" - state of queue -> empty
String c = stringQueue.peek() // Returns null
String d = stringQueue.element() // Throws NoSuchElementException

// Assuming `stringQueue` has elements -> "Mike", "Jack", "John"
for (String name: stringQueue) {
  System.out.println(name);
}
// OUTPUT TERMINAL: "Mike", "Jack", "John"
content_copyCOPY