queue接口

 在java5中新增加了java.util.Queue接口,用以支持队列的常见操作。该接口扩展了java.util.Collection接口。
Queue使用时要尽量避免Collection的add()和remove()方法,而是要使用offer()来加入元素,使用poll()来获取并移出元素。它们的优
点是通过返回值可以判断成功与否,add()和remove()方法在失败的时候会抛出异常。 如果要使用而不移出该元素,用
element()或者peek()方法。
值得注意的是LinkedList类实现了Deque(双向)接口,而Deque继承了Queue接口,因此我们可以把LinkedList当成Queue来用。
import java.util.Queue; 
import java.util.LinkedList; 
public class TestQueue { 
    public static void main(String[] args) { 
        Queue<String> queue = new LinkedList<String>(); 
        queue.offer("Hello"); 
        queue.offer("World!"); 
        queue.offer("你好!"); 
        System.out.println(queue.size()); 
        String str; 
        System.out.println(queue.element());
        System.out.println(queue.peek());
        System.out.println(queue.remove("World!"));
        System.out.println(queue.peek());
        while((str=queue.poll())!=null){ 
            System.out.print(str); 
        } 
        System.out.println(); 
        System.out.println(queue.size()); 
    } 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值