Saturday, 27 August 2016

What difference between element, peer and poll of Queue


In a Queue, element is added at the tail and retrieved from the head.

using 'add' and 'offer' to add element on tail.
using 'element' 'peer' and 'poll' to retrieve element on head.

Difference
'element' and 'peer' are able to retrieve the head, but don't remove it;  but for 'pool', which retrieving head and  removing it .

In Java, LinkedList implements Queue interface; in another word, Queue is implemented by the LinkedList.


/**
 *
 * @author YNZ
 */
public class UseLinkedList {

    public static void main(String[] args) {

        LinkedList linkedPersons = new LinkedList<>();
        Random r = new Random();
        char a = 'A';
        for (int i = 1; i < 4; i++) {
            if (a > 'Z') {
                break;
            }
            String name = String.valueOf(a).concat(String.valueOf(a));
            linkedPersons.add(new Person(name, r.nextInt(100)));
            a++;
        }
        
        Queue queue = linkedPersons;
        System.out.println("Initial Q = " + queue);
        
        Person head = queue.element();
        System.out.println("after element = " + head);
        System.out.println("Q = " + queue);
        
        Person peek = queue.peek();
        System.out.println("after peek = " + peek);
        System.out.println("Q = " + queue);
        
        Person poll = queue.poll();
        System.out.println("after poll = " + poll);
        
        System.out.println("Q = " + queue);

    }

}



run:
Initial Q = [AA 42, BB 46, CC 72]
after element = AA 42
Q = [AA 42, BB 46, CC 72]
after peek = AA 42
Q = [AA 42, BB 46, CC 72]
after poll = AA 42
Q = [BB 46, CC 72]
BUILD SUCCESSFUL (total time: 0 seconds)



No comments:

Can Jackson Deserialize Java Time ZonedDateTime

Yes, but must include JSR310. Thus ZonedDateTime can be deserialized directly from JSON response to POJO field. <dependency> <g...