Queue:
- 1.5Version enhancements (Queue interface)
- It is the child interface of Collection
- If we want to represent group of individual objects prior to processing then we should go for Queue.
- For Example Before sending SMS messages all mobile numbers we have to store in some data structure. In which we ordered mobile numbers in the same order only message should be delivered. For this First In First Out requirement Queue is best choice.
- Usually, Queue follows First In First Out order. Based on our requirement we can implement our own priority order also. (Priority Queue).
- From 1.5 version also LinkedList class implements Queue interface.
- LinkedList based implementation of the Queue always follows First In First Out order.
Queue interface specific methods:
to add an object into the Queue
to return head element of the queue. If the queue is empty then this method returns null.
to return head element of the queue. If the queue is empty then this method raises RE: NoSuchElementException
to remove and return head element of the queue. If the queue is empty then this method returns null
to remove and return head element of the queue. If the queue is empty then this method raises RE: NoSuchElementException
PriorityQueue:
- If we want to represent a group of individual objects prior to processing according to some priority then we should go for PriorityQueue.
- The priority can be either default natural sorting order or customized sorting order defined by Comparator.
- Insertion order is not preserved and 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 and Comparable otherwise, we will get runtime exception saying ClassCastException.
- If we are defining our own sorting by Comparator then objects need not be homogenous and Comparable.
- Null is not allowed even as a first element also.
Constructors:
creates an empty PriorityQueue with default initial capacity 11 and all objects will be inserted according to default natural sorting order.
Output:
null
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0
[1, 3, 2, 7, 4, 5, 6, 10, 8, 9]
Note: Some platforms won’t provide proper support for Thread priorities and PriorityQueues.
Output:
[siva, kalyan, hemanth, chanukya]
0 Comments