What is the difference between the add and offer methods in a Queue in Java?

前端 未结 8 1483
盖世英雄少女心
盖世英雄少女心 2020-12-12 13:29

Take the PriorityQueue for example http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html#offer(E)

Can anyone give me an example of a Queu

8条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 13:52

    I will write the java contract example code for offer method and add method showing how they differ.

    BlockingQueue queue = new ArrayBlockingQueue<>(2);
            queue.add("TestQuue1");     
            queue.add("TestQuue2"); 
            queue.add("TestQuue3");  // will throw "java.lang.IllegalStateException: Queue full
    
    BlockingQueue queue = new ArrayBlockingQueue<>(2);
            queue.offer("TestQuue1");       
            queue.offer("TestQuue2");   
            queue.offer("TestQuue3"); // will not throw any exception
    

提交回复
热议问题