Sunday 22 January 2012

Queue example in java

Before going into the details of this program, it is advised to go through Queue Fundamentals where queue basics were discussed.
Following are some methods that do the similar operations.
  • boolean offer(Object obj): Adds the element obj to the queue. If the addition is successful, the method returns true else false.
  • Object poll(): Returns the head (first) element and also deletes it. That is, we cannot get it again. If no element exists (when queue is empty), the method returns null.
  • Object remove(): It also returns and deletes the head element like poll(), but with a small difference. This method throws NoSuchElementException if the queue is empty.
  • Object peek(): Returns the head element but it does not delete it. That is, we can get it again. Returns null when the queue is empty.
  • Object element(): It works similar to peek() but with a small difference (returns but does not delete the element). It throws NoSuchElementException when the queue is empty.
offer() method is equivalent to add() method of Collection interface.
http://way2java.com/collections/queue-programming/

No comments:

Post a Comment