欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java Queue (LinkedList)代码示例,queuelinkedlist,Queue接口实现了Co

来源: javaer 分享于  点击 14894 次 点评:79

java Queue (LinkedList)代码示例,queuelinkedlist,Queue接口实现了Co


Queue接口实现了Collection接口并且支持FIFO先进先出弹出元素。

这意味着当我们声明一个空的Queue对象并添加一个元素后,这个元素会第一个被移除。Queue和List最大的不同在于用List可以通过get(i)方法获得任意位置的元素,而用Queue则必须先进先出。需要注意LinkedList类实现了List和Queue两个接口,也就是说LinkedList支持这两个接口的行为。

如下示例代码:

import java.util.LinkedList;import java.util.Queue;/** * * @author byrx.net */public class Main {    /**     * Example method for using a Queue     */    public void queueExample() {        Queue queue = new LinkedList();        //Using the add method to add items.        //Should anything go wrong an exception will be thrown.        queue.add("item1");        queue.add("item2");        //Using the offer method to add items.        //Should anything go wrong it will just return false        queue.offer("Item3");        queue.offer("Item4");        //Removing the first item from the queue.        //If the queue is empty a java.util.NoSuchElementException will be thrown.         System.out.println("remove: " + queue.remove());        //Checking what item is first in line without removing it        //If the queue is empty a java.util.NoSuchElementException will be thrown.         System.out.println("element: " + queue.element());        //Removing the first item from the queue.        //If the queue is empty the method just returns false.         System.out.println("poll: " + queue.poll());        //Checking what item is first in line without removing it        //If the queue is empty a null value will be returned.         System.out.println("peek: " + queue.peek());    }    /**     * @param args the command line arguments     */    public static void main(String[] args) {        new Main().queueExample();    }}

输出:

remove: item1element: item2poll: item2peek: Item3
相关栏目:

用户点评