Monday, September 4, 2017

Java - Queue Interface

Source Link:
https://stackoverflow.com/questions/4626812/how-do-i-instantiate-a-queue-object-in-java

Notes:
1. Queue in Java is defined as an interface.
2. Many ready-to-use implementation (is present as part of JDK release)
3. Here are some: LinkedList, Priority Queue, ArrayBlockingQueue, etc.

Example: 
import java.util.LinkedList; 
import java.util.Queue;
public class QueueExample {
 public static void main (String[] args) 
  Queue que = new LinkedList(); 
  que.add("first");
  que.offer("second");
  que.offer("third");
  System.out.println("Queue Print:: " + que);

  String head = que.element();
  System.out.println("Head element:: " + head);

  String element1 = que.poll();
  System.out.println("Removed Element:: " + element1);

  System.out.println("Queue Print after poll:: " + que);
  String element2 = que.remove();
  System.out.println("Removed Element:: " + element2);

  System.out.println("Queue Print after remove:: " + que);  
 }
} 
some more notes: 
1. The add and offer methods have the same semantics. 
2. The remove() and poll() methods differ only in their behavior when the queue is empty. 
3. The remove() method throws an exception, while the poll() method returns null.

No comments:

Post a Comment

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...