/**
* 队列存取元素遵循先进先出原则
* @author Heying_He
*
*/
public static void main(String[] args) {
firstQueue();
System.out.println("**************FUN2*****************");
pollQueue();
}
/**
* poll() 从队首移除并返回该元素 出队<br>
* peek() 引用队首元素,该操作不会将队首元素移除
*/
public static void firstQueue(){
Queue<String> queue = new LinkedList<String>();
queue.add("A");
queue.add("B");
queue.add("C");
System.out.println(queue);
/*
* 从队首移除并返回该元素 出队
* poll
*/
String e = queue.poll();
System.out.println("队首是>> "+e);
System.out.println(queue);
/*
* peek()方法:
* 引用队首元素,该操作不会将队首元素移除
*/
e = queue.peek();
System.out.println("peek 之后的队首是>> "+e);
System.out.println(queue);
}
public static void pollQueue(){
Queue<String> queue = new LinkedList<String>();
queue.add("1");
queue.add("2");
queue.add("3");
System.out.println(queue);
// peek
for (int i = queue.size(); i > 0; i-- ) { // 每次poll队列数量都会减少,要用减法
System.out.println(queue.peek());
}
System.out.println("#####>> peek over");
// 1
for (int i = queue.size(); i > 0; i-- ) { // 每次poll队列数量都会减少,要用减法
System.out.println(queue.poll());
}
// 2 遍历
System.out.println("###########>> poll over");
queue.add("1");
queue.add("2");
queue.add("3");
for (String queuer : queue) {
System.out.println(queuer);
}
// 3
System.out.println("###########");
while(queue.size() > 0){ // ***当队列为空时,poll方法返回null***
System.out.println(queue.poll());
}
}
队列进出原则
最新推荐文章于 2023-12-18 14:23:15 发布