Queue
- 1.5(v) enhancement of Queue(I).
- It is the child Interface of Collection.
- If we want to represent a group of individual objects Prior to Processing than we should go for Queue.
- for eg: Before sending sms message all mobile no. we have to store all mobile no. in some data structure. In which order we added mobile no. in same order only message should be delivered for this FIFO requirement Queue is the best choice.
- Usually Queue follows First In First Out [FIFO] order but based on our requirement we can implement our own Priority order also [Priority Queue].
- From (1.5v) onwards LinkedList class also implements Queue Interface.
- LinkedList based implementation of Queue always First In First Out [FIFO] order.
- boolean offer(Object o)
- To add an object into the Queue.
- Object peek()
- To return head element of the queue. If Queue is empty than this method return Null.
- Object element()
- To return head element of the queue. If queue is empty than this method raise RE:NoSuchElementException.
- Object poll()
- To remove & return head element of the queue.If Queue is empty than this method return Null.
- Object remove()
- To remove & return head element of the queue. If queue is empty than this method raise RE:NoSuchElementException.
For eg:
- q.peek() it returns head element of queue but if the queue is empty than it returns Null.
For eg:
- if we are calling q.element() or q.remove() of queue,if the queue is empty than it returns RE:NoSuchElementException.
For eg:
output:
- poll() it means remove & returns head element of queue here 0 is the head element.
- After remove head element 1 is the head element now output is 1,2,3...
Priority Queue
- If we want to represent a group of individual objects Prior to processing according to some priority than, we should go for PriorityQueue.
- The priority can be either Default Natural Sorting or Customizer Sorting order defined by Comparator.
- Insertion Order is not preserved & it is based on some priority.
- Duplicate objects are not allowed.
- If we are depending on Default Natural Sorting order compulsory the object should be Homogeneous & comparable otherwise we will get RE:ClassCastException.
- If we are defining our own sorting by Comparator than objects need not be Homogeneous & Comparable.
- Null is not allowed even as the first element also.
Constructor
- PriorityQueue q = new PriorityQueue();
- Creates an empty priority with default intial capacity is 11. all object will be inserted according to Default Natural Sorting order.
- PriorityQueue q = new PriorityQueue(int intialCapacity);
- PriorityQueue q = new PriorityQueue(int intialCapacity Comparator);
- PriorityQueue q = new PriorityQueue(SortedSet s);
- PriorityQueue q = new PriorityQueue(Collection c);
Note:
- Some platform won't provide proper support for Thread priorities & priorityQueues.
For eg of Customizer Sorting:
Matri Sharma
No comments:
Post a Comment