日期:2014-05-20  浏览次数:20670 次

怎样判断这个队伍是否满了?
比如我创造一个队伍,书上说如果满了,用offer添加会返回false,我不明白的是怎样知道已经满了。比如下面的程序
import java.util.Queue;
import java.util.LinkedList;

public class Test
{
public static void main(String[] args)
{
Queue<String> list = new LinkedList<String>();
list.add("abc");
list.add("eee");
list.add("fff");

}
}

我是把new LinkedList<String>();写成new LinkedList<String>(3);吗?但是会有错误?如果括号中不指定个数,在哪里知道它会满?
------解决方案--------------------

Queue<String> queue = new ArrayBlockingQueue<String>(3);    
        queue.add("abc");
        queue.add("eee");
        queue.add("fff"); 
        queue.add("efa");  
        System.out.println(queue);

在你向队列add一个元素的时候,queue会先检查当前队列的长度,要是达到你之前定义的长度,则会抛异常,告诉你queue full
------解决方案--------------------

上面,当加第四个元素"efa"时,在例行检查队列长度时,发现队列已满,抛异常
------解决方案--------------------
用LinkedBlockingQueue试试:
Queue<String> list = new LinkedBlockingQueue<String>(2); 
------解决方案--------------------
 /**
     * Adds the specified element as the tail (last element) of this list.
     *
     * @param e the element to add
     * @return {@code true} (as specified by {@link Queue#offer})
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }

这段是offer方法的源码,jdk1.5之后跟直接使用add是无什么区别的。不要尽信书,有时也不必去验证书上的每个理论,注重实际使用。如果你要指定队列的大小,满了之后要执行相应的逻辑,可以使用楼上的方法,cache到异常执行相应的操作就行。
------解决方案--------------------
没初始化大小。