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:
Post a Comment