Java中的队列Queue的相关用法及介绍

版权声明:转载注明来源。Keep Learning and Coding. https://blog.csdn.net/a771581211/article/details/88424996
package day05;

import java.util.LinkedList;
import java.util.Queue;

/**
 * java.util.Queue
 * 队列
 * 队列也可以存放一组元素,但是存放元素必须遵循:先进先出原则。
 * @author kaixu
 *
 */
public class QueueDemo {

	public static void main(String[] args) {
		/*
		 * LinkedList也实现了队列接口,因为它可以保存一组元素
		 * 并且首尾增删快,正好符合队列的特点。
		 */
		Queue<String> queue = new LinkedList<String>();
		/*
		 * boolean offer(E e)
		 * 入队操作,向队尾追加一个新元素。
		 */
		queue.offer("one");
		queue.offer("two");
		queue.offer("three");
		queue.offer("four");
		System.out.println(queue);  //[one, two, three, four]
		/*
		 * E poll()
		 * 出队操作,从队首获取元素
		 * 获取该元素后它将从队列中被删除。
		 */
		String str = queue.poll();
		System.out.println(str);  //one
		System.out.println(queue);  //[two, three, four]
		/*
		 * E peek()
		 * 引用队首元素,但是不做出队操作。
		 */
		str = queue.peek();
		System.out.println(str);  //two
		System.out.println(queue);  //[two, three, four]
		
		System.out.println("遍历开始");
		System.out.println("size:"+queue.size());
		//for(int i=queue.size();i>0;i--){
		//	str = queue.poll();
		//	System.out.println("元素:"+str);  //此处使用for循环并不理想,改用while
		//}
			while(queue.size()>0){
				str = queue.poll();
				System.out.println("元素:"+str);
			}
			
			System.out.println("遍历完毕");
			System.out.println(queue);
	}

}

猜你喜欢

转载自blog.csdn.net/a771581211/article/details/88424996
今日推荐