- The AP subset requires students to know the following methods of the
java.util.Queue
interface:
void add(Object item)
//Adds item to the end of the Queue.
boolean isEmpty()
//Returns true if the Queue has no elements.
Object peek()
//Returns the top element without removing it.
Object remove()
//Returns and removes the first element.
- To declare a reference variable for a Queue, do the following:
Queue <ClassName> myQ =
new LinkedList <ClassName> ();
-
This is an easy way to create a new Queue object without having to create a whole new class to implement the Queue interface. There are other ways to implement a Queue but this is the only way that AP requires.
- Here is a short example showing how to create, populate, and deconstruct a Queue.
Queue <Integer> q = new LinkedList <Integer> ();
for(int i = 1; i <= 5; i++){
q.add(i);
}
for(Integer temp : q){
System.out.println(temp);
}
while(!q.isEmpty()){
System.out.println(q.remove());
}
Output:
1
2
3
4
5
1
2
3
4
5
In this example, both loops print the exact same thing. This is because a Queue adds data to the end and takes data from the front, so it is going from the front to the end when removing data, just like the for each loop.